<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/safari-pinned-tab.svg" color="#222">
  <link rel="stylesheet" href="/css/main.css">
  <link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>
  <script id="hexo-configurations">
    var NexT = window.NexT ||
    {};
    var CONFIG = {
      "hostname": "cuiqingcai.com",
      "root": "/",
      "scheme": "Pisces",
      "version": "7.8.0",
      "exturl": false,
      "sidebar":
      {
        "position": "right",
        "width": 360,
        "display": "post",
        "padding": 18,
        "offset": 12,
        "onmobile": false,
        "widgets": [
          {
            "type": "image",
            "name": "阿布云",
            "enable": false,
            "url": "https://www.abuyun.com/http-proxy/introduce.html",
            "src": "https://qiniu.cuiqingcai.com/88au8.jpg",
            "width": "100%"
      },
          {
            "type": "image",
            "name": "天验",
            "enable": true,
            "url": "https://tutorial.lengyue.video/?coupon=12ef4b1a-a3db-11ea-bb37-0242ac130002_cqx_850",
            "src": "https://qiniu.cuiqingcai.com/bco2a.png",
            "width": "100%"
      },
          {
            "type": "image",
            "name": "华为云",
            "enable": false,
            "url": "https://activity.huaweicloud.com/2020_618_promotion/index.html?bpName=5f9f98a29e2c40b780c1793086f29fe2&bindType=1&salesID=wangyubei",
            "src": "https://qiniu.cuiqingcai.com/y42ik.jpg",
            "width": "100%"
      },
          {
            "type": "image",
            "name": "张小鸡",
            "enable": false,
            "url": "http://www.zxiaoji.com/",
            "src": "https://qiniu.cuiqingcai.com/fm72f.png",
            "width": "100%"
      },
          {
            "type": "image",
            "name": "Luminati",
            "src": "https://qiniu.cuiqingcai.com/ikkq9.jpg",
            "url": "https://luminati-china.io/?affiliate=ref_5fbbaaa9647883f5c6f77095",
            "width": "100%",
            "enable": false
      },
          {
            "type": "image",
            "name": "IPIDEA",
            "url": "http://www.ipidea.net/?utm-source=cqc&utm-keyword=?cqc",
            "src": "https://qiniu.cuiqingcai.com/0ywun.png",
            "width": "100%",
            "enable": true
      },
          {
            "type": "tags",
            "name": "标签云",
            "enable": true
      },
          {
            "type": "categories",
            "name": "分类",
            "enable": true
      },
          {
            "type": "friends",
            "name": "友情链接",
            "enable": true
      },
          {
            "type": "hot",
            "name": "猜你喜欢",
            "enable": true
      }]
      },
      "copycode":
      {
        "enable": true,
        "show_result": true,
        "style": "mac"
      },
      "back2top":
      {
        "enable": true,
        "sidebar": false,
        "scrollpercent": true
      },
      "bookmark":
      {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": true,
      "comments":
      {
        "style": "tabs",
        "active": "gitalk",
        "storage": true,
        "lazyload": false,
        "nav": null,
        "activeClass": "gitalk"
      },
      "algolia":
      {
        "hits":
        {
          "per_page": 10
        },
        "labels":
        {
          "input_placeholder": "Search for Posts",
          "hits_empty": "We didn't find any results for the search: ${query}",
          "hits_stats": "${hits} results found in ${time} ms"
        }
      },
      "localsearch":
      {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 10,
        "unescape": false,
        "preload": false
      },
      "motion":
      {
        "enable": false,
        "async": false,
        "transition":
        {
          "post_block": "bounceDownIn",
          "post_header": "slideDownIn",
          "post_body": "slideDownIn",
          "coll_header": "slideLeftIn",
          "sidebar": "slideUpIn"
        }
      },
      "path": "search.xml"
    };

  </script>
  <meta name="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
  <meta property="og:type" content="website">
  <meta property="og:title" content="静觅">
  <meta property="og:url" content="https://cuiqingcai.com/page/28/index.html">
  <meta property="og:site_name" content="静觅">
  <meta property="og:description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
  <meta property="og:locale" content="zh_CN">
  <meta property="article:author" content="崔庆才">
  <meta property="article:tag" content="崔庆才">
  <meta property="article:tag" content="静觅">
  <meta property="article:tag" content="PHP">
  <meta property="article:tag" content="Java">
  <meta property="article:tag" content="Python">
  <meta property="article:tag" content="Spider">
  <meta property="article:tag" content="爬虫">
  <meta property="article:tag" content="Web">
  <meta property="article:tag" content="Kubernetes">
  <meta property="article:tag" content="深度学习">
  <meta property="article:tag" content="机器学习">
  <meta property="article:tag" content="数据分析">
  <meta property="article:tag" content="网络">
  <meta property="article:tag" content="IT">
  <meta property="article:tag" content="技术">
  <meta property="article:tag" content="博客">
  <meta name="twitter:card" content="summary">
  <link rel="canonical" href="https://cuiqingcai.com/page/28/">
  <script id="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: true,
      isPost: false,
      lang: 'zh-CN'
    };

  </script>
  <title>静觅丨崔庆才的个人站点</title>
  <meta name="google-site-verification" content="p_bIcnvirkFzG2dYKuNDivKD8-STet5W7D-01woA2fc" />
  <noscript>
    <style>
      .use-motion .brand,
      .use-motion .menu-item,
      .sidebar-inner,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header
      {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle
      {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line-before i
      {
        left: initial;
      }

      .use-motion .logo-line-after i
      {
        right: initial;
      }

    </style>
  </noscript>
  <link rel="alternate" href="/atom.xml" title="静觅" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏">
              <span class="toggle-line toggle-line-first"></span>
              <span class="toggle-line toggle-line-middle"></span>
              <span class="toggle-line toggle-line-last"></span>
            </div>
          </div>
          <div class="site-meta">
            <a href="/" class="brand" rel="start">
              <span class="logo-line-before"><i></i></span>
              <h1 class="site-title">静觅 <span class="site-subtitle"> 崔庆才的个人站点 </span>
              </h1>
              <span class="logo-line-after"><i></i></span>
            </a>
          </div>
          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>
        <nav class="site-nav">
          <ul id="menu" class="main-menu menu">
            <li class="menu-item menu-item-home">
              <a href="/" rel="section">首页</a>
            </li>
            <li class="menu-item menu-item-archives">
              <a href="/archives/" rel="section">文章列表</a>
            </li>
            <li class="menu-item menu-item-tags">
              <a href="/tags/" rel="section">文章标签</a>
            </li>
            <li class="menu-item menu-item-categories">
              <a href="/categories/" rel="section">文章分类</a>
            </li>
            <li class="menu-item menu-item-about">
              <a href="/about/" rel="section">关于博主</a>
            </li>
            <li class="menu-item menu-item-message">
              <a href="/message/" rel="section">给我留言</a>
            </li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger">搜索 </a>
            </li>
          </ul>
        </nav>
        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div id="search-result">
              <div id="no-result">
                <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </header>
    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>
    <div class="reading-progress-bar"></div>
    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div class="content index posts-expand">
            <div class="carousel">
              <div id="wowslider-container">
                <div class="ws_images">
                  <ul>
                    <li><a target="_blank" href="https://cuiqingcai.com/5052.html"><img title="Python3网络爬虫开发实战教程" src="https://qiniu.cuiqingcai.com/ipy96.jpg" /></a></li>
                    <li><a target="_blank" href="https://t.lagou.com/fRCBRsRCSN6FA"><img title="52讲轻松搞定网络爬虫" src="https://qiniu.cuiqingcai.com/fqq5e.png" /></a></li>
                    <li><a target="_blank" href="https://brightdata.grsm.io/cuiqingcai"><img title="亮网络解锁器" src="https://qiniu.cuiqingcai.com/6qnb7.png" /></a></li>
                    <li><a target="_blank" href="https://cuiqingcai.com/4320.html"><img title="Python3网络爬虫开发视频教程" src="https://qiniu.cuiqingcai.com/bjrny.jpg" /></a></li>
                    <li><a target="_blank" href="https://cuiqingcai.com/5094.html"><img title="爬虫代理哪家强？十大付费代理详细对比评测出炉！" src="https://qiniu.cuiqingcai.com/nifs6.jpg" /></a></li>
                  </ul>
                </div>
                <div class="ws_thumbs">
                  <div>
                    <a target="_blank" href="#"><img src="https://qiniu.cuiqingcai.com/ipy96.jpg" /></a>
                    <a target="_blank" href="#"><img src="https://qiniu.cuiqingcai.com/fqq5e.png" /></a>
                    <a target="_blank" href="#"><img src="https://qiniu.cuiqingcai.com/6qnb7.png" /></a>
                    <a target="_blank" href="#"><img src="https://qiniu.cuiqingcai.com/bjrny.jpg" /></a>
                    <a target="_blank" href="#"><img src="https://qiniu.cuiqingcai.com/nifs6.jpg" /></a>
                  </div>
                </div>
                <div class="ws_shadow"></div>
              </div>
            </div>
            <link rel="stylesheet" href="/lib/wowslide/slide.css">
            <script src="/lib/wowslide/jquery.min.js"></script>
            <script src="/lib/wowslide/slider.js"></script>
            <script>
              jQuery("#wowslider-container").wowSlider(
              {
                effect: "cube",
                prev: "",
                next: "",
                duration: 20 * 100,
                delay: 20 * 100,
                width: 716,
                height: 297,
                autoPlay: true,
                playPause: true,
                stopOnHover: false,
                loop: false,
                bullets: 0,
                caption: true,
                captionEffect: "slide",
                controls: true,
                onBeforeStep: 0,
                images: 0
              });

            </script>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1304.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> 福利专区 <i class="label-arrow"></i>
                  </a>
                  <a href="/1304.html" class="post-title-link" itemprop="url">简单两步用百度网盘轻松收取文件</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>向多人收取文件，并保存于百度盘中，适合收取作业啦，资源啦等等。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/03/2015-03-09-233806-的屏幕截图-e1425915588634.png" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/03/2015-03-09-233806-的屏幕截图-e1425915588634.png" alt="2015-03-09 23:38:06 的屏幕截图"></a> 这个比较有意思，两步就可以创建一个页面，用于接收任何人发送的文件。 为它授权百度盘账号后，就可以设定一下接收内容了，比如头部颜色、LOGO、名称，说明等等。 文件接收时间最长 30 天，收到的文件位于百度网盘 &gt; 我的应用数据 &gt; DzzCloud 下，然后就没有然后了。 小团队、学校、办公室等地方用于接收多人文件、作业太适合不过了，无需注册打开即可上传。 福利链接 <a href="http://xzc.cn/?t=Dn0W727yDH" target="_blank" rel="noopener">向我传送</a><a href="http://xzc.cn/" target="_blank" rel="noopener">官方地址</a></p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-03-09 23:46:17" itemprop="dateCreated datePublished" datetime="2015-03-09T23:46:17+08:00">2015-03-09</time>
                </span>
                <span id="/1304.html" class="post-meta-item leancloud_visitors" data-flag-title="简单两步用百度网盘轻松收取文件" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>218</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>1 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1290.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> PHP <i class="label-arrow"></i>
                  </a>
                  <a href="/1290.html" class="post-title-link" itemprop="url">PHP高级特性三之文件上传和下载</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <h2 id="综述"><a href="#综述" class="headerlink" title="综述"></a>综述</h2>
                  <p>上一节我们学习了文件的读写操作，这一节我们来看一下文件上传和下载的相关内容。</p>
                  <h2 id="文件上传"><a href="#文件上传" class="headerlink" title="文件上传"></a>文件上传</h2>
                  <h3 id="1-PHP配置文件"><a href="#1-PHP配置文件" class="headerlink" title="1.PHP配置文件"></a>1.PHP配置文件</h3>
                  <p>首先，我们文件上传需要设定一下 php.ini 的配置文件。这是最基本的设置，如果这里设置不成功，那么代码写得再正确也没有用。基本的配置项目如下</p>
                  <blockquote>
                    <p>file_uploads = on #文件上传开启 upload_max_filesize= 200M #文件上传的最大尺寸 upload_tmp_dir = c:/uploads/ #临时文件目录 post_max_size = 250M #POST时最大尺寸，必须要大于 upload_max_filesize</p>
                  </blockquote>
                  <h3 id="2-上传时注意事项"><a href="#2-上传时注意事项" class="headerlink" title="2.上传时注意事项"></a>2.上传时注意事项</h3>
                  <p>1） 文件上传操作表单提交方法必须为 post 2）文件上传时，input type 必须为 file 类型 3）文件上传的表单中，需要增加一个隐含内容，代码如下，value 的单位是 B</p>
                  <figure class="highlight pgsql">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;<span class="keyword">input</span> <span class="keyword">type</span>="hidden" <span class="type">name</span>="MAX_FILE_SIZE" <span class="keyword">value</span>="100000000"&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>4）enctype=”multipart/form-data” 只有文件上传时才使用这个值，用来指定表单编码的数据方式，让服务器知道我们要传递一个文件并带有一些常规的表单信息。如下</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">"upload.php"</span> <span class="attr">method</span>=<span class="string">"post"</span> <span class="attr">enctype</span>=<span class="string">"multipart/form-data"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>例如</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">title</span>&gt;</span> File Uploads <span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">head</span>&gt;</span> </span><br><span class="line"> <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">"b.php"</span> <span class="attr">method</span>=<span class="string">"post"</span> <span class="attr">enctype</span>=<span class="string">"multipart/form-data"</span>&gt;</span></span><br><span class="line"> shopname: <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"shopname"</span> &gt;</span> <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line"> shopprice: <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"price"</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line"> shopnum : <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"num"</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line"> shoppic: <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"file"</span> <span class="attr">name</span>=<span class="string">"pic"</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span> <span class="attr">name</span>=<span class="string">"sub"</span> <span class="attr">value</span>=<span class="string">"添加商品"</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">form</span>&gt;</span> </span><br><span class="line"> <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>文件 a.php 表单提交到了 b.php 文件，在文件 b.php 中如下</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> <span class="string">"&lt;pre&gt;"</span>;</span></span><br><span class="line"><span class="php"> print_r($_POST);</span></span><br><span class="line"><span class="php"> print_r($_FILES);</span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> <span class="string">"&lt;/pre&gt;"</span>;</span></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>一个是输出 POST得到的数据内容，另一个是输出获取到的文件信息。 运行结果如下</p>
                  <figure class="highlight php">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">Array</span></span><br><span class="line">(</span><br><span class="line">    [shopname] =&gt; abc</span><br><span class="line">    [price] =&gt; abc</span><br><span class="line">    [num] =&gt; add</span><br><span class="line">    [sub] =&gt; 添加商品</span><br><span class="line">)</span><br><span class="line"><span class="keyword">Array</span></span><br><span class="line">(</span><br><span class="line">    [pic] =&gt; <span class="keyword">Array</span></span><br><span class="line">        (</span><br><span class="line">            [name] =&gt; QPGF.dll</span><br><span class="line">            [type] =&gt; application/qscall-plugin</span><br><span class="line">            [tmp_name] =&gt; D:\wamp\tmp\phpC2C7.tmp</span><br><span class="line">            [error] =&gt; <span class="number">0</span></span><br><span class="line">            [size] =&gt; <span class="number">199224</span></span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>如果不加 enctype=”multipart/form-data” 那么 print_r($_FILES) 不会有任何输出 又比如<strong>多文件上传</strong></p>
                  <figure class="highlight vim">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="symbol">&lt;html&gt;</span></span><br><span class="line"> <span class="symbol">&lt;head&gt;</span></span><br><span class="line"> <span class="symbol">&lt;title&gt;</span> File Uploads &lt;/title&gt;</span><br><span class="line"> &lt;/head&gt; </span><br><span class="line"> <span class="symbol">&lt;body&gt;</span></span><br><span class="line"> &lt;form action=<span class="string">"b.php"</span> method=<span class="string">"post"</span> enctype=<span class="string">"multipart/form-data"</span>&gt;</span><br><span class="line"> shopname: &lt;<span class="built_in">input</span> <span class="built_in">type</span>=<span class="string">"text"</span> name=<span class="string">"shopname"</span> &gt; <span class="symbol">&lt;br&gt;</span></span><br><span class="line"> shopprice: &lt;<span class="built_in">input</span> <span class="built_in">type</span>=<span class="string">"text"</span> name=<span class="string">"price"</span>&gt; <span class="symbol">&lt;br&gt;</span></span><br><span class="line"> shopnum : &lt;<span class="built_in">input</span> <span class="built_in">type</span>=<span class="string">"text"</span> name=<span class="string">"num"</span>&gt; <span class="symbol">&lt;br&gt;</span></span><br><span class="line"> shoppic: &lt;<span class="built_in">input</span> <span class="built_in">type</span>=<span class="string">"file"</span> name=<span class="string">"pic1"</span>&gt; <span class="symbol">&lt;br&gt;</span></span><br><span class="line"> shoppic: &lt;<span class="built_in">input</span> <span class="built_in">type</span>=<span class="string">"file"</span> name=<span class="string">"pic2"</span>&gt; <span class="symbol">&lt;br&gt;</span></span><br><span class="line"> shoppic: &lt;<span class="built_in">input</span> <span class="built_in">type</span>=<span class="string">"file"</span> name=<span class="string">"pic3"</span>&gt; <span class="symbol">&lt;br&gt;</span></span><br><span class="line"> &lt;<span class="built_in">input</span> <span class="built_in">type</span>=<span class="string">"submit"</span> name=<span class="string">"sub"</span> value=<span class="string">"添加商品"</span>&gt;</span><br><span class="line"> &lt;/form&gt; </span><br><span class="line"> &lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>file的name需要不同的名字，那么上面的代码输出结果为</p>
                  <figure class="highlight php">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">Array</span></span><br><span class="line">(</span><br><span class="line">    [pic1] =&gt; <span class="keyword">Array</span></span><br><span class="line">        (</span><br><span class="line">            [name] =&gt; libtcmalloc.dll</span><br><span class="line">            [type] =&gt; application/qscall-plugin</span><br><span class="line">            [tmp_name] =&gt; D:\wamp\tmp\phpE51E.tmp</span><br><span class="line">            [error] =&gt; <span class="number">0</span></span><br><span class="line">            [size] =&gt; <span class="number">178232</span></span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">    [pic2] =&gt; <span class="keyword">Array</span></span><br><span class="line">        (</span><br><span class="line">            [name] =&gt; libexpatw.dll</span><br><span class="line">            [type] =&gt; application/qscall-plugin</span><br><span class="line">            [tmp_name] =&gt; D:\wamp\tmp\phpE52E.tmp</span><br><span class="line">            [error] =&gt; <span class="number">0</span></span><br><span class="line">            [size] =&gt; <span class="number">130104</span></span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">    [pic3] =&gt; <span class="keyword">Array</span></span><br><span class="line">        (</span><br><span class="line">            [name] =&gt; AsyncTask.dll</span><br><span class="line">            [type] =&gt; application/qscall-plugin</span><br><span class="line">            [tmp_name] =&gt; D:\wamp\tmp\phpE52F.tmp</span><br><span class="line">            [error] =&gt; <span class="number">0</span></span><br><span class="line">            [size] =&gt; <span class="number">84536</span></span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>还可以将name设定为一个数组，如</p>
                  <figure class="highlight pgsql">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">shoppic: &lt;<span class="keyword">input</span> <span class="keyword">type</span>="file" <span class="type">name</span>="pic[]"&gt; &lt;br&gt;</span><br><span class="line">shoppic: &lt;<span class="keyword">input</span> <span class="keyword">type</span>="file" <span class="type">name</span>="pic[]"&gt; &lt;br&gt;</span><br><span class="line">shoppic: &lt;<span class="keyword">input</span> <span class="keyword">type</span>="file" <span class="type">name</span>="pic[]"&gt; &lt;br&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>则输出会是一个三维数组</p>
                  <figure class="highlight php">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">Array</span></span><br><span class="line">(</span><br><span class="line">    [pic] =&gt; <span class="keyword">Array</span></span><br><span class="line">        (</span><br><span class="line">            [name] =&gt; <span class="keyword">Array</span></span><br><span class="line">                (</span><br><span class="line">                    [<span class="number">0</span>] =&gt; libtcmalloc.dll</span><br><span class="line">                    [<span class="number">1</span>] =&gt; libexpatw.dll</span><br><span class="line">                    [<span class="number">2</span>] =&gt; QQProtect.dll</span><br><span class="line">                )</span><br><span class="line"></span><br><span class="line">            [type] =&gt; <span class="keyword">Array</span></span><br><span class="line">                (</span><br><span class="line">                    [<span class="number">0</span>] =&gt; application/qscall-plugin</span><br><span class="line">                    [<span class="number">1</span>] =&gt; application/qscall-plugin</span><br><span class="line">                    [<span class="number">2</span>] =&gt; application/qscall-plugin</span><br><span class="line">                )</span><br><span class="line"></span><br><span class="line">            [tmp_name] =&gt; <span class="keyword">Array</span></span><br><span class="line">                (</span><br><span class="line">                    [<span class="number">0</span>] =&gt; D:\wamp\tmp\phpA17D.tmp</span><br><span class="line">                    [<span class="number">1</span>] =&gt; D:\wamp\tmp\phpA17E.tmp</span><br><span class="line">                    [<span class="number">2</span>] =&gt; D:\wamp\tmp\phpA17F.tmp</span><br><span class="line">                )</span><br><span class="line"></span><br><span class="line">            [error] =&gt; <span class="keyword">Array</span></span><br><span class="line">                (</span><br><span class="line">                    [<span class="number">0</span>] =&gt; <span class="number">0</span></span><br><span class="line">                    [<span class="number">1</span>] =&gt; <span class="number">0</span></span><br><span class="line">                    [<span class="number">2</span>] =&gt; <span class="number">0</span></span><br><span class="line">                )</span><br><span class="line"></span><br><span class="line">            [size] =&gt; <span class="keyword">Array</span></span><br><span class="line">                (</span><br><span class="line">                    [<span class="number">0</span>] =&gt; <span class="number">178232</span></span><br><span class="line">                    [<span class="number">1</span>] =&gt; <span class="number">130104</span></span><br><span class="line">                    [<span class="number">2</span>] =&gt; <span class="number">387128</span></span><br><span class="line">                )</span><br><span class="line"></span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="3-文件上传后的检查"><a href="#3-文件上传后的检查" class="headerlink" title="3. 文件上传后的检查"></a>3. 文件上传后的检查</h3>
                  <p>加入上传的表单中文件的name是pic，那么检查的四个方法如下： 1）使用 $_FILES[‘file’][‘error’] 检查错误 2）使用 $_FILES[‘file’][‘size’] 限制大小，单位是字节 3）使用 $_FILES[‘pic’][‘type’] 获取文件或站名，限制文件的类型 4）将上传后的文件名改名</p>
                  <figure class="highlight bash">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;?php</span><br><span class="line">	//step 1 使用<span class="variable">$_FILES</span>[<span class="string">'pic'</span>][<span class="string">"error"</span>] 检查错误</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span>(<span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"error"</span>] &gt; 0)&#123;</span><br><span class="line">		switch(<span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"error"</span>]) &#123;</span><br><span class="line">			<span class="keyword">case</span> 1:</span><br><span class="line">				<span class="built_in">echo</span> <span class="string">"上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值&lt;br&gt;"</span>;</span><br><span class="line">                  <span class="built_in">break</span>;</span><br><span class="line">			<span class="keyword">case</span> 2:</span><br><span class="line">				<span class="built_in">echo</span> <span class="string">"上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值"</span>;</span><br><span class="line">				<span class="built_in">break</span>;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">case</span> 3: </span><br><span class="line">				<span class="built_in">echo</span> <span class="string">"文件只有部分被上传"</span>;</span><br><span class="line">				<span class="built_in">break</span>;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">case</span> 4:</span><br><span class="line">				<span class="built_in">echo</span> <span class="string">"没有文件被上传"</span>;</span><br><span class="line">				<span class="built_in">break</span>;</span><br><span class="line"></span><br><span class="line">			default:</span><br><span class="line"></span><br><span class="line">				<span class="built_in">echo</span> <span class="string">"末知错误"</span>;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">		<span class="built_in">exit</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="variable">$maxsize</span>=5000000;  //50k</span><br><span class="line"></span><br><span class="line">	//step 2 使用<span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"size"</span>] 限制大小 单位字节 2M=2000000</span><br><span class="line">	<span class="keyword">if</span>(<span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"size"</span>] &gt; <span class="variable">$maxsize</span> ) &#123;</span><br><span class="line">		<span class="built_in">echo</span> <span class="string">"上传的文件太大，不能超过&#123;<span class="variable">$maxsize</span>&#125;字节"</span>;</span><br><span class="line">		<span class="built_in">exit</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	//step 3 使用<span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"type"</span>]或是文件的扩展名 限制类型 MIME  image/gif  image/png    gif png jpg</span><br><span class="line"></span><br><span class="line">	/*   list(<span class="variable">$dl</span>, <span class="variable">$xl</span>) = explode(<span class="string">"/"</span>, <span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"type"</span>]);</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span>(<span class="variable">$dl</span>!=<span class="string">"image"</span>)&#123;</span><br><span class="line">			<span class="built_in">echo</span> <span class="string">"请上传一个图片，不充许其它类型文件"</span>;</span><br><span class="line">			<span class="built_in">exit</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	 */</span><br><span class="line">	</span><br><span class="line">	<span class="variable">$allowtype</span>=array(<span class="string">"png"</span>, <span class="string">"gif"</span>, <span class="string">"jpg"</span>, <span class="string">"jpeg"</span>);</span><br><span class="line">	<span class="variable">$arr</span>=explode(<span class="string">"."</span>, <span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"name"</span>]);</span><br><span class="line">	<span class="variable">$hz</span>=<span class="variable">$arr</span>[count(<span class="variable">$arr</span>)-1];</span><br><span class="line">	<span class="keyword">if</span>(!in_array(<span class="variable">$hz</span>, <span class="variable">$allowtype</span>))&#123;</span><br><span class="line">		<span class="built_in">echo</span> <span class="string">"这是不充许的类型"</span>;</span><br><span class="line">		<span class="built_in">exit</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	//step 4 将让传后的文件名改名</span><br><span class="line"></span><br><span class="line">	</span><br><span class="line">	<span class="variable">$filepath</span>=<span class="string">"./uploads/"</span>;</span><br><span class="line">	<span class="variable">$randname</span>=date(<span class="string">"Y"</span>).date(<span class="string">"m"</span>).date(<span class="string">"d"</span>).date(<span class="string">"H"</span>).date(<span class="string">"i"</span>).date(<span class="string">"s"</span>).rand(100, 999).<span class="string">"."</span>.<span class="variable">$hz</span>;</span><br><span class="line">	//将临时位置的文件移动到指定的目录上即可</span><br><span class="line">	<span class="keyword">if</span>(is_uploaded_file(<span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"tmp_name"</span>]))&#123;</span><br><span class="line">		<span class="keyword">if</span>(move_uploaded_file(<span class="variable">$_FILES</span>[<span class="string">"pic"</span>][<span class="string">"tmp_name"</span>], <span class="variable">$filepath</span>.<span class="variable">$randname</span>))&#123;</span><br><span class="line">			<span class="built_in">echo</span> <span class="string">"上传成功"</span>;</span><br><span class="line">		&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">			<span class="built_in">echo</span> <span class="string">"上传失败"</span>;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">		<span class="built_in">echo</span> <span class="string">"不是一个上传文件"</span>;</span><br><span class="line">	&#125;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>以上便实现了文件上传的检测，包括错误检测，文件大小检测，文件类型检测以及文件更名等等。</p>
                  <h2 id="文件上传类"><a href="#文件上传类" class="headerlink" title="文件上传类"></a>文件上传类</h2>
                  <p>在上面的介绍中，我们没有将文件的上传做一个封装，不过，将文件上传个功能封装成一个类的确是一个不错的选择。下面便是一个实例DEMO，让我们来感受一下吧！</p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="module-access"><span class="module"><span class="identifier">FileUpload</span>.</span></span><span class="keyword">class</span>.php</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span></span></span><br><span class="line"><span class="php">	<span class="class"><span class="keyword">class</span> <span class="title">FileUpload</span> </span>&#123;</span></span><br><span class="line"><span class="php">	</span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $filePath;     <span class="comment">//指定上传文件保存的路径</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $allowType=<span class="keyword">array</span>(<span class="string">'gif'</span>, <span class="string">'jpg'</span>, <span class="string">'png'</span>, <span class="string">'jpeg'</span>);  <span class="comment">//充许上传文件的类型</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $maxSize=<span class="number">1000000</span>;  <span class="comment">//允上传文件的最大长度 1M</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $isRandName=<span class="keyword">true</span>;  <span class="comment">//是否随机重命名， true false不随机，使用原文件名</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $originName;   <span class="comment">//源文件名称</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $tmpFileName;   <span class="comment">//临时文件名</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $fileType;  <span class="comment">//文件类型</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $fileSize;  <span class="comment">//文件大小</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $newFileName; <span class="comment">//新文件名</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $errorNum=<span class="number">0</span>;  <span class="comment">//错误号</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> $errorMess=<span class="string">""</span>; <span class="comment">//用来提供错误报告</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="php">		<span class="comment">//用于对上传文件初使化</span></span></span><br><span class="line"><span class="php">		<span class="comment">//1. 指定上传路径， 2，充许的类型， 3，限制大小， 4，是否使用随机文件名称</span></span></span><br><span class="line"><span class="php">		<span class="comment">//让用户可以不用按位置传参数，后面参数给值不用将前几个参数也提供值</span></span></span><br><span class="line"><span class="php">		<span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">($options=array<span class="params">()</span>)</span></span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">foreach</span>($options <span class="keyword">as</span> $key=&gt;$val)&#123;</span></span><br><span class="line"><span class="php">				<span class="comment">//查看用户参数中数组的下标是否和成员属性名相同</span></span></span><br><span class="line"><span class="php">				<span class="keyword">if</span>(!in_array($key,get_class_vars(get_class(<span class="keyword">$this</span>))))&#123;</span></span><br><span class="line"><span class="php">					<span class="keyword">continue</span>;</span></span><br><span class="line"><span class="php">				&#125;</span></span><br><span class="line"><span class="php">				<span class="comment">//设置成员变量</span></span></span><br><span class="line"><span class="php">				<span class="keyword">$this</span>-&gt;setOption($key, $val);</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">	</span></span><br><span class="line"></span><br><span class="line"><span class="php">		<span class="comment">//获得错误原因</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">getError</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="php">			<span class="comment">//获得错误原因</span></span></span><br><span class="line"><span class="php">			$str=<span class="string">"上传文件&lt;font color='red'&gt;&#123;$this-&gt;originName&#125;&lt;/font&gt;时出错："</span>;</span></span><br><span class="line"><span class="php">			<span class="keyword">switch</span>(<span class="keyword">$this</span>-&gt;errorNum)&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">4</span>: $str .= <span class="string">"没有文件被上传"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">3</span>: $str .= <span class="string">"文件只被部分上传"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">2</span>: $str .= <span class="string">"上传文件超过了HTML表单中MAX_FILE_SIZE选项指定的值"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">1</span>: $str .= <span class="string">"上传文件超过了php.ini 中upload_max_filesize选项的值"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">-1</span>: $str .= <span class="string">"不被充许的类型"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">-2</span>: $str .= <span class="string">"文件过大，上传文件不能超过&#123;$this-&gt;maxSize&#125;个字节"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">-3</span>: $str .= <span class="string">"上传失败"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">-4</span>: $str .= <span class="string">"建立存放上传文件目录失败，请重新指定上传目录"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">case</span> <span class="number">-5</span>: $str .= <span class="string">"必须指定上传文件的路径"</span>; <span class="keyword">break</span>;</span></span><br><span class="line"><span class="php">				<span class="keyword">default</span>: $str .=  <span class="string">"末知错误"</span>;</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">			<span class="keyword">return</span> $str.<span class="string">'&lt;br&gt;'</span>;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">	</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">		<span class="comment">//用来检查文件上传路径</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">checkFilePath</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>(<span class="keyword">empty</span>(<span class="keyword">$this</span>-&gt;filePath)) &#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">$this</span>-&gt;setOption(<span class="string">'errorNum'</span>, <span class="number">-5</span>);</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> <span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>(!file_exists(<span class="keyword">$this</span>-&gt;filePath) || !is_writable(<span class="keyword">$this</span>-&gt;filePath))&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">if</span>(!@mkdir(<span class="keyword">$this</span>-&gt;filePath, <span class="number">0755</span>))&#123;</span></span><br><span class="line"><span class="php">					<span class="keyword">$this</span>-&gt;setOption(<span class="string">'errorNum'</span>, <span class="number">-4</span>);</span></span><br><span class="line"><span class="php">					<span class="keyword">return</span> <span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">				&#125;</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">			<span class="keyword">return</span> <span class="keyword">true</span>;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">		<span class="comment">//用来检查文件上传的大小</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">checkFileSize</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>(<span class="keyword">$this</span>-&gt;fileSize &gt; <span class="keyword">$this</span>-&gt;maxSize)&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">$this</span>-&gt;setOPtion(<span class="string">'errorNum'</span>, <span class="string">'-2'</span>);</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> <span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">			&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> <span class="keyword">true</span>;</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="php">		<span class="comment">//用于检查文件上传类型</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">checkFileType</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>(in_array(strtolower(<span class="keyword">$this</span>-&gt;fileType), <span class="keyword">$this</span>-&gt;allowType)) &#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> <span class="keyword">true</span>;</span></span><br><span class="line"><span class="php">			&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">$this</span>-&gt;setOption(<span class="string">'errorNum'</span>, <span class="number">-1</span>);</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> <span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">		<span class="comment">//设置上传后的文件名称</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">setNewFileName</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>(<span class="keyword">$this</span>-&gt;isRandName)&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">$this</span>-&gt;setOption(<span class="string">'newFileName'</span>, <span class="keyword">$this</span>-&gt;proRandName());</span></span><br><span class="line"><span class="php">			&#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">$this</span>-&gt;setOption(<span class="string">'newFileName'</span>, <span class="keyword">$this</span>-&gt;originName);</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="php">		<span class="comment">//设置随机文件名称</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">proRandName</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="php">			$fileName=date(<span class="string">"YmdHis"</span>).rand(<span class="number">100</span>,<span class="number">999</span>);</span></span><br><span class="line"><span class="php">			<span class="keyword">return</span> $fileName.<span class="string">'.'</span>.<span class="keyword">$this</span>-&gt;fileType;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">		<span class="comment">//设置成员变量</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">setOption</span><span class="params">($key, $val)</span></span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">$this</span>-&gt;$key=$val;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">		<span class="comment">//用来上传一个文件</span></span></span><br><span class="line"><span class="php">		<span class="function"><span class="keyword">function</span> <span class="title">uploadFile</span><span class="params">($fileField)</span></span>&#123;</span></span><br><span class="line"><span class="php">			</span></span><br><span class="line"><span class="php">			<span class="keyword">echo</span> $fileField;</span></span><br><span class="line"><span class="php">			<span class="comment">//默认返回值为True</span></span></span><br><span class="line"><span class="php">			$return=<span class="keyword">true</span>;</span></span><br><span class="line"><span class="php">			<span class="comment">//首先检查文件上传路径</span></span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>(!<span class="keyword">$this</span>-&gt;checkFilePath())&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">$this</span>-&gt;errorMess=<span class="keyword">$this</span>-&gt;getError();</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> <span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="php">			<span class="comment">//获得上传文件的名字</span></span></span><br><span class="line"><span class="php">			$name=$_FILES[$fileField][<span class="string">'name'</span>];</span></span><br><span class="line"><span class="php">			<span class="comment">//获得临时文件名</span></span></span><br><span class="line"><span class="php">			$tmp_name=$_FILES[$fileField][<span class="string">'tmp_name'</span>];</span></span><br><span class="line"><span class="php">			<span class="comment">//获得上传文件的大小</span></span></span><br><span class="line"><span class="php">			$size=$_FILES[$fileField][<span class="string">'size'</span>];</span></span><br><span class="line"><span class="php">			<span class="comment">//获得上传错误代号</span></span></span><br><span class="line"><span class="php">			$error=$_FILES[$fileField][<span class="string">'error'</span>];</span></span><br><span class="line"><span class="php">			</span></span><br><span class="line"><span class="php">			<span class="comment">//如果上传的是多个文件</span></span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>(is_Array($name))&#123;</span></span><br><span class="line"><span class="php">				<span class="comment">//错误代号必须也是Array，因为一个文件对应一个错误代号</span></span></span><br><span class="line"><span class="php">				$errors=<span class="keyword">array</span>();</span></span><br><span class="line"><span class="php">				<span class="comment">//遍历检查文件</span></span></span><br><span class="line"><span class="php">				<span class="keyword">for</span>($i=<span class="number">0</span>; $i&lt;count($name); $i++)&#123;</span></span><br><span class="line"><span class="php">					<span class="keyword">if</span>(<span class="keyword">$this</span>-&gt;setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i]))&#123;</span></span><br><span class="line"><span class="php">						<span class="keyword">if</span>(!<span class="keyword">$this</span>-&gt;checkFileSize() || !<span class="keyword">$this</span>-&gt;checkFileType())&#123;</span></span><br><span class="line"><span class="php">							$errors[]=<span class="keyword">$this</span>-&gt;getError();</span></span><br><span class="line"><span class="php">							$return=<span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">						&#125;</span></span><br><span class="line"><span class="php">					&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">						$error[]=<span class="keyword">$this</span>-&gt;getError();</span></span><br><span class="line"><span class="php">						$return=<span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">					&#125;</span></span><br><span class="line"><span class="php">					<span class="keyword">if</span>(!$return)</span></span><br><span class="line"><span class="php">						<span class="keyword">$this</span>-&gt;setFiles();</span></span><br><span class="line"><span class="php">				&#125;</span></span><br><span class="line"><span class="php">				<span class="keyword">if</span>($return)&#123;</span></span><br><span class="line"><span class="php">					$fileNames=<span class="keyword">array</span>();</span></span><br><span class="line"><span class="php">					<span class="keyword">for</span>($i=<span class="number">0</span>; $i&lt;count($name); $i++)&#123;</span></span><br><span class="line"><span class="php">						<span class="keyword">if</span>(<span class="keyword">$this</span>-&gt;setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i]))&#123;</span></span><br><span class="line"><span class="php">							<span class="keyword">$this</span>-&gt;setNewFileName();</span></span><br><span class="line"><span class="php">							<span class="keyword">if</span>(!<span class="keyword">$this</span>-&gt;copyFile())&#123;</span></span><br><span class="line"><span class="php">								$errors=<span class="keyword">$this</span>-&gt;getError();</span></span><br><span class="line"><span class="php">								$return=<span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">							&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">								$fileNames[]=<span class="keyword">$this</span>-&gt;newFileName;</span></span><br><span class="line"><span class="php">							&#125;</span></span><br><span class="line"><span class="php">						&#125;</span></span><br><span class="line"><span class="php">					&#125;</span></span><br><span class="line"><span class="php">					<span class="comment">//是一个数组</span></span></span><br><span class="line"><span class="php">					<span class="keyword">$this</span>-&gt;newFileName=$fileNames;</span></span><br><span class="line"><span class="php">				&#125;</span></span><br><span class="line"><span class="php">				<span class="comment">//赋值错误信息</span></span></span><br><span class="line"><span class="php">				<span class="keyword">$this</span>-&gt;errorMess=$errors;</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> $return;</span></span><br><span class="line"><span class="php">			<span class="comment">//如果是单个文件上传</span></span></span><br><span class="line"><span class="php">			&#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="php">					<span class="keyword">if</span>(<span class="keyword">$this</span>-&gt;setFiles($name, $tmp_name, $size, $error))&#123;</span></span><br><span class="line"><span class="php">						<span class="keyword">if</span>(<span class="keyword">$this</span>-&gt;checkFileSize() &amp;&amp; <span class="keyword">$this</span>-&gt;checkFileType())&#123;</span></span><br><span class="line"><span class="php">							<span class="keyword">$this</span>-&gt;setNewFileName();</span></span><br><span class="line"><span class="php">							<span class="keyword">if</span>(<span class="keyword">$this</span>-&gt;copyFile())&#123;</span></span><br><span class="line"><span class="php">								<span class="keyword">return</span> <span class="keyword">true</span>;</span></span><br><span class="line"><span class="php">							&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">								$return=<span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">							&#125;</span></span><br><span class="line"><span class="php">						&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">							$return=<span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">						&#125;	</span></span><br><span class="line"><span class="php">					&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">						$return=<span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">					&#125;</span></span><br><span class="line"><span class="php">					</span></span><br><span class="line"><span class="php">					<span class="keyword">if</span>(!$return)</span></span><br><span class="line"><span class="php">						<span class="keyword">$this</span>-&gt;errorMess=<span class="keyword">$this</span>-&gt;getError();</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="php">					<span class="keyword">return</span> $return;</span></span><br><span class="line"><span class="php">			&#125;			</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">		<span class="comment">//保存文件,将文件从临时路径移动到新路径</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">copyFile</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>(!<span class="keyword">$this</span>-&gt;errorNum)&#123;</span></span><br><span class="line"><span class="php">				$filePath=rtrim(<span class="keyword">$this</span>-&gt;filePath, <span class="string">'/'</span>).<span class="string">'/'</span>;</span></span><br><span class="line"><span class="php">				$filePath.=<span class="keyword">$this</span>-&gt;newFileName;</span></span><br><span class="line"></span><br><span class="line"><span class="php">				<span class="keyword">if</span>(@move_uploaded_file(<span class="keyword">$this</span>-&gt;tmpFileName, $filePath))	&#123;</span></span><br><span class="line"><span class="php">					<span class="keyword">return</span> <span class="keyword">true</span>;</span></span><br><span class="line"><span class="php">				&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">					<span class="keyword">$this</span>-&gt;setOption(<span class="string">'errorNum'</span>, <span class="number">-3</span>);</span></span><br><span class="line"><span class="php">					<span class="keyword">return</span> <span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">				&#125;</span></span><br><span class="line"><span class="php">					</span></span><br><span class="line"><span class="php">			&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> <span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="php">		<span class="comment">//设置和$_FILES有关的内容</span></span></span><br><span class="line"><span class="php">		<span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">setFiles</span><span class="params">($name=<span class="string">""</span>, $tmp_name=<span class="string">''</span>, $size=<span class="number">0</span>, $error=<span class="number">0</span>)</span></span>&#123;</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">			<span class="keyword">$this</span>-&gt;setOption(<span class="string">'errorNum'</span>, $error);</span></span><br><span class="line"><span class="php">			<span class="keyword">if</span>($error)&#123;</span></span><br><span class="line"><span class="php">				<span class="keyword">return</span> <span class="keyword">false</span>;</span></span><br><span class="line"><span class="php">			&#125;</span></span><br><span class="line"><span class="php">			<span class="keyword">$this</span>-&gt;setOption(<span class="string">'originName'</span>, $name);</span></span><br><span class="line"><span class="php">			<span class="keyword">$this</span>-&gt;setOption(<span class="string">'tmpFileName'</span>, $tmp_name);</span></span><br><span class="line"><span class="php">			<span class="comment">//分割文件名，取最后一个后缀</span></span></span><br><span class="line"><span class="php">			$arrStr=explode(<span class="string">'.'</span>, $name); </span></span><br><span class="line"><span class="php">			<span class="keyword">$this</span>-&gt;setOption(<span class="string">'fileType'</span>, strtolower($arrStr[count($arrStr)<span class="number">-1</span>]));</span></span><br><span class="line"><span class="php">			<span class="keyword">$this</span>-&gt;setOption(<span class="string">'fileSize'</span>, $size);	</span></span><br><span class="line"><span class="php">			<span class="keyword">return</span> <span class="keyword">true</span>;</span></span><br><span class="line"><span class="php">		&#125;	</span></span><br><span class="line"></span><br><span class="line"><span class="php">		<span class="comment">//用于获取上传后文件的文件名</span></span></span><br><span class="line"><span class="php">		<span class="function"><span class="keyword">function</span> <span class="title">getNewFileName</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">return</span> <span class="keyword">$this</span>-&gt;newFileName;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">		<span class="comment">//上传如果失败，则调用这个方法，就可以查看错误报告</span></span></span><br><span class="line"><span class="php">		<span class="function"><span class="keyword">function</span> <span class="title">getErrorMsg</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="php">			<span class="keyword">return</span> <span class="keyword">$this</span>-&gt;errorMess;</span></span><br><span class="line"><span class="php">		&#125;</span></span><br><span class="line"><span class="php">		</span></span><br><span class="line"><span class="php">	&#125;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"> <span class="selector-tag">upload</span><span class="selector-class">.php</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span></span></span><br><span class="line"><span class="php">	<span class="keyword">require</span> <span class="string">"FileUpload.class.php"</span>;</span></span><br><span class="line"><span class="php">	<span class="comment">//实例化这个对象</span></span></span><br><span class="line"><span class="php">	$up=<span class="keyword">new</span> FileUpload(<span class="keyword">array</span>(<span class="string">'isRandName'</span>=&gt;<span class="keyword">true</span>,<span class="string">'allowType'</span>=&gt;<span class="keyword">array</span>(<span class="string">'txt'</span>, <span class="string">'doc'</span>, <span class="string">'php'</span>, <span class="string">'gif'</span>),<span class="string">'filePath'</span>=&gt;<span class="string">'./uploads/'</span>, <span class="string">'maxSize'</span>=&gt;<span class="number">200000</span>));</span></span><br><span class="line"><span class="php">	<span class="keyword">echo</span> <span class="string">'&lt;pre&gt;'</span>;</span></span><br><span class="line"><span class="php">	<span class="comment">//调用上传文件的方法</span></span></span><br><span class="line"><span class="php">	<span class="keyword">if</span>($up-&gt;uploadFile(<span class="string">'upload'</span>))&#123;</span></span><br><span class="line"><span class="php">		print_r($up-&gt;getNewFileName());</span></span><br><span class="line"><span class="php">	&#125;<span class="keyword">else</span>&#123;</span></span><br><span class="line"><span class="php">		print_r($up-&gt;getErrorMsg());	</span></span><br><span class="line"><span class="php">	&#125;</span></span><br><span class="line"><span class="php">	<span class="keyword">echo</span> <span class="string">'&lt;/pre&gt;'</span>;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"> <span class="selector-tag">form</span><span class="selector-class">.html</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight pgsql">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;form action="upload.php" <span class="keyword">method</span>="post" enctype="multipart/form-data"&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="hidden" <span class="type">name</span>="MAX_FILE_SIZE" <span class="keyword">value</span>="100000000"&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="file" <span class="type">name</span>="upload"&gt; &lt;br&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="submit" <span class="type">name</span>="sub" <span class="keyword">value</span>="upload file"&gt;&lt;br&gt;</span><br><span class="line">&lt;/form&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"> 多文件上传的 <span class="selector-tag">form</span><span class="selector-class">.html</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight pgsql">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;form action="upload.php" <span class="keyword">method</span>="post" enctype="multipart/form-data"&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="hidden" <span class="type">name</span>="MAX_FILE_SIZE" <span class="keyword">value</span>="100000000"&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="file" <span class="type">name</span>="upload[]"&gt; &lt;br&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="file" <span class="type">name</span>="upload[]"&gt; &lt;br&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="file" <span class="type">name</span>="upload[]"&gt; &lt;br&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="file" <span class="type">name</span>="upload[]"&gt; &lt;br&gt;</span><br><span class="line">	&lt;<span class="keyword">input</span> <span class="keyword">type</span>="submit" <span class="type">name</span>="sub" <span class="keyword">value</span>="upload file"&gt;&lt;br&gt;</span><br><span class="line">&lt;/form&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>利用上面的这个文件上传类，我们便可以轻松地实现文件上传，非常之便捷。</p>
                  <h2 id="文件下载"><a href="#文件下载" class="headerlink" title="文件下载"></a>文件下载</h2>
                  <p>对于浏览器无法直接打开的文件，我们一般只需要设置一下超链接就好了。比如</p>
                  <figure class="highlight livecodeserver">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;<span class="keyword">a</span> href=<span class="string">"a.rar"</span>&gt;<span class="keyword">a</span>.rar&lt;/<span class="keyword">a</span>&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>点击超链接之后，便会弹出下载的提示框。 可是对于浏览器可以直接打开的文件，例如 1.html，2.php，3.gif 等等文件，如果仍然用这种超链接形式，那就行不通了，浏览器会直接跳转到这个页面。 我们怎样解决这个问题呢？很简单 我们首先要将超链接的文件名改为一个 php 文件，比如上面的链接就可以改为</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"a.php"</span>&gt;</span>logo.gif<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>这样浏览器会去访问 a.php 文件，那么我们只需要在 a.php 文件中作相应处理即可，例如我们要下载 logo.gif 文件 我们就需要在 a.php 文件最开始设定头部信息，如下</p>
                  <figure class="highlight lasso">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;?php </span><br><span class="line">	<span class="keyword">header</span>(<span class="string">"Content-Type:image/gif"</span>);</span><br><span class="line">	<span class="keyword">header</span>(<span class="string">'Content-Disposition: attachment; filename="logo.gif"'</span>);</span><br><span class="line">	<span class="keyword">header</span>(<span class="string">'Content-Length:300'</span>);</span><br><span class="line">    readfile(<span class="string">"logo.gif"</span>);</span><br><span class="line"><span class="meta">?&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>一般设置三个头部信息就好了 第一个是设置文件传输的类型，第二个是设置传送的内容为附件形式，文件名是 logo.gif，这里的filename 即为我们下载文件时命名的名字，而不是文件名本身。第三个是设置文件传输大小。 最后设置一下下载的是哪个文件就好了。利用 readfile 方法。 以上便是文件下载所需要的方法。 这样，文件上传和文件下载的方法就全部介绍完啦！</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-03-09 14:12:47" itemprop="dateCreated datePublished" datetime="2015-03-09T14:12:47+08:00">2015-03-09</time>
                </span>
                <span id="/1290.html" class="post-meta-item leancloud_visitors" data-flag-title="PHP高级特性三之文件上传和下载" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>12k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>11 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1278.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> JavaScript <i class="label-arrow"></i>
                  </a>
                  <a href="/1278.html" class="post-title-link" itemprop="url">JavaScript高级用法四之DOM对象</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <h2 id="综述"><a href="#综述" class="headerlink" title="综述"></a>综述</h2>
                  <p>本篇的主要内容来自慕课网，DOM对象，主要内容如下</p>
                  <ul>
                    <li>1 认识DOM</li>
                    <li>2 getElementsByName()方法</li>
                    <li>3 getElementsByTagName()方法</li>
                    <li>4 区别getElementByID,getElementsByName,getElementsByTagName</li>
                    <li>5 getAttribute()方法</li>
                    <li>6 setAttribute()方法</li>
                    <li>7 节点属性</li>
                    <li>8 访问子结点childNodes</li>
                    <li>9 访问子结点的第一和最后项</li>
                    <li>10 访问父节点parentNode</li>
                    <li>11 访问兄弟节点</li>
                    <li>12 插入节点appendChild()</li>
                    <li>13 插入节点insertBefore()</li>
                    <li>14 删除节点removeChild()</li>
                    <li>15 替换元素节点replaceChild()</li>
                    <li>16 创建元素节点createElement</li>
                    <li>17 创建文本节点createTextNode</li>
                    <li>18 浏览器窗口可视区域大小</li>
                    <li>19 网页尺寸scrollHeight</li>
                    <li>20 网页尺寸offsetHeight</li>
                    <li>21 网页卷去的距离与偏移量</li>
                  </ul>
                  <h2 id="认识DOM"><a href="#认识DOM" class="headerlink" title="认识DOM"></a>认识DOM</h2>
                  <p>文档对象模型DOM（Document Object Model）定义访问和处理HTML文档的标准方法。DOM 将HTML文档呈现为带有元素、属性和文本的树结构（节点树）。 <strong>先来看看下面代码:</strong> <a href="http://img.mukewang.com/5375ca640001c67307860420.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5375ca640001c67307860420.jpg" alt=""></a></p>
                  <p><strong>将HTML代码分解为DOM节点层次图:</strong></p>
                  <p><a href="http://img.mukewang.com/5375ca7e0001dd8d04830279.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5375ca7e0001dd8d04830279.jpg" alt=""></a> <strong>HTML**</strong>文档可以说由节点构成的集合，DOM节点有:<strong> </strong>1.<strong> </strong>元素节点：<strong>上图中<html>、

                      <body>、<p>等都是元素节点，即标签。 </strong>2.<strong> </strong>文本节点:<strong>向用户展示的内容，如<li>...</li>中的JavaScript、DOM、CSS等文本。 </strong>3.<strong> </strong>属性节点:<strong>元素属性，如<a>标签的链接属性href=”<a href="http://www.imooc.com&quot;。" target="_blank" rel="noopener">http://www.imooc.com&quot;。</a> </strong>节点属性:<strong> <a href="http://img.mukewang.com/5375c953000117ee05240129.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5375c953000117ee05240129.jpg" alt=""></a> </strong>遍历节点树:<strong> <a href="http://img.mukewang.com/53f17a6400017d2905230219.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53f17a6400017d2905230219.jpg" alt=""></a> </strong>以上图ul为例，它的父级节点body,它的子节点3个li,它的兄弟结点h2、P。<strong> </strong>DOM操作:** <a href="http://img.mukewang.com/538d29da000152db05360278.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/538d29da000152db05360278.jpg" alt=""></a></p>
                  <h2 id="getElementsByName-方法"><a href="#getElementsByName-方法" class="headerlink" title="getElementsByName()方法"></a>getElementsByName()方法</h2>
                  <p>返回带有指定名称的节点对象的集合。</p>
                  <p><strong>语法：</strong></p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">document.get<span class="constructor">ElementsByName(<span class="params">name</span>)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>与getElementById() 方法不同的是，通过元素的 name 属性查询元素，而不是通过 id 属性。</p>
                  <p><strong>注意:</strong></p>
                  <ol>
                    <li>
                      <p>因为文档中的 name 属性可能不唯一，所有 getElementsByName() 方法返回的是元素的数组，而不是一个元素。</p>
                    </li>
                    <li>
                      <p>和数组类似也有length属性，可以和访问数组一样的方法来访问，从0开始。</p>
                    </li>
                  </ol>
                  <p><strong>看看下面的代码:</strong></p>
                  <p><a href="http://img.mukewang.com/5375d5ec00012bac06210322.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5375d5ec00012bac06210322.jpg" alt=""></a></p>
                  <p><strong>运行结果:</strong></p>
                  <p><a href="http://img.mukewang.com/53795f0b0001233404580318.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53795f0b0001233404580318.jpg" alt=""></a></p>
                  <h2 id="getElementsByTagName-方法"><a href="#getElementsByTagName-方法" class="headerlink" title="getElementsByTagName()方法"></a>getElementsByTagName()方法</h2>
                  <p>返回带有指定标签名的节点对象的集合。返回元素的顺序是它们在文档中的顺序。 <strong>语法:</strong></p>
                  <figure class="highlight stylus">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="function"><span class="title">getElementsByTagName</span><span class="params">(Tagname)</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>说明:</strong> 1. Tagname是标签的名称，如p、a、img等标签名。 2. 和数组类似也有length属性，可以和访问数组一样的方法来访问，所以从0开始。 看看下面代码，通过getElementsByTagName()获取节点。 <a href="http://img.mukewang.com/53ec174a0001404206540436.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53ec174a0001404206540436.jpg" alt=""></a></p>
                  <h2 id="区别getElementByID-getElementsByName-getElementsByTagName"><a href="#区别getElementByID-getElementsByName-getElementsByTagName" class="headerlink" title="区别getElementByID,getElementsByName,getElementsByTagName"></a>区别getElementByID,getElementsByName,getElementsByTagName</h2>
                  <p><strong>以人来举例说明，人有能标识身份的身份证，有姓名，有类别(大人、小孩、老人)等。</strong> 1. ID 是一个人的身份证号码，是唯一的。所以通过getElementById获取的是指定的一个人。 2. Name 是他的名字，可以重复。所以通过getElementsByName获取名字相同的人集合。 3. TagName可看似某类，getElementsByTagName获取相同类的人集合。如获取小孩这类人，getElementsByTagName(“小孩”)。 <strong>把上面的例子转换到HTML中，如下:</strong></p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"checkbox"</span> <span class="attribute">name</span>=<span class="string">"hobby"</span> <span class="attribute">id</span>=<span class="string">"hobby1"</span>&gt;  音乐</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>input标签就像人的类别。 name属性就像人的姓名。 id属性就像人的身份证。 <strong>方法总结如下:</strong> <a href="http://img.mukewang.com/5405263300018bcf05760129.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5405263300018bcf05760129.jpg" alt=""></a> <strong>注意：</strong>方法区分大小写 通过下面的例子(6个name=”hobby”的复选项，两个按钮)来区分三种方法的不同:</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"checkbox"</span> <span class="attribute">name</span>=<span class="string">"hobby"</span> <span class="attribute">id</span>=<span class="string">"hobby1"</span>&gt;  音乐</span><br><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"checkbox"</span> <span class="attribute">name</span>=<span class="string">"hobby"</span> <span class="attribute">id</span>=<span class="string">"hobby2"</span>&gt;  登山</span><br><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"checkbox"</span> <span class="attribute">name</span>=<span class="string">"hobby"</span> <span class="attribute">id</span>=<span class="string">"hobby3"</span>&gt;  游泳</span><br><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"checkbox"</span> <span class="attribute">name</span>=<span class="string">"hobby"</span> <span class="attribute">id</span>=<span class="string">"hobby4"</span>&gt;  阅读</span><br><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"checkbox"</span> <span class="attribute">name</span>=<span class="string">"hobby"</span> <span class="attribute">id</span>=<span class="string">"hobby5"</span>&gt;  打球</span><br><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"checkbox"</span> <span class="attribute">name</span>=<span class="string">"hobby"</span> <span class="attribute">id</span>=<span class="string">"hobby6"</span>&gt;  跑步 </span><br><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"button"</span> value = <span class="string">"全选"</span> <span class="attribute">id</span>=<span class="string">"button1"</span>&gt;</span><br><span class="line">&lt;input <span class="attribute">type</span>=<span class="string">"button"</span> value = <span class="string">"全不选"</span> <span class="attribute">id</span>=<span class="string">"button1"</span>&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>1. document.getElementsByTagName(“input”)，结果为获取所有标签为input的元素，共8个。 2. document.getElementsByName(“hobby”)，结果为获取属性name=”hobby”的元素，共6个。 3. document.getElementById(“hobby6”)，结果为获取属性id=”hobby6”的元素，只有一个，”跑步”这个复选项。</p>
                  <h2 id="getAttribute-方法"><a href="#getAttribute-方法" class="headerlink" title="getAttribute()方法"></a>getAttribute()方法</h2>
                  <p>通过元素节点的属性名称获取属性的值。 <strong>语法：</strong></p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">elementNode.get<span class="constructor">Attribute(<span class="params">name</span>)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>说明:</strong> 1. elementNode：使用getElementById()、getElementsByTagName()等方法，获取到的元素节点。 2. name：要想查询的元素节点的属性名字 看看下面的代码，获取h1标签的属性值： <a href="http://img.mukewang.com/538d242700019ec809330432.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/538d242700019ec809330432.jpg" alt=""></a> <strong>运行结果:</strong> h1标签的ID ：alink h1标签的title ：getAttribute()获取标签的属值</p>
                  <h2 id="setAttribute-方法"><a href="#setAttribute-方法" class="headerlink" title="setAttribute()方法"></a>setAttribute()方法</h2>
                  <p>setAttribute() 方法增加一个指定名称和值的新属性，或者把一个现有的属性设定为指定的值。 <strong>语法：</strong></p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">elementNode.set<span class="constructor">Attribute(<span class="params">name</span>,<span class="params">value</span>)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>说明：</strong> 1.name: 要设置的属性名。 2.value: 要设置的属性值。 <strong>注意：</strong> 1.把指定的属性设置为指定的值。如果不存在具有指定名称的属性，该方法将创建一个新属性。 2.类似于getAttribute()方法，setAttribute()方法只能通过元素节点对象调用的函数。</p>
                  <h2 id="节点属性"><a href="#节点属性" class="headerlink" title="节点属性"></a>节点属性</h2>
                  <p>在文档对象模型 (DOM) 中，每个节点都是一个对象。DOM 节点有三个重要的属性 ： 1. nodeName : 节点的名称 2. nodeValue ：节点的值 3. nodeType ：节点的类型 <strong>一、nodeName 属性:</strong> 节点的名称，是只读的。 1. 元素节点的 nodeName 与标签名相同 2. 属性节点的 nodeName 是属性的名称 3. 文本节点的 nodeName 永远是 #text 4. 文档节点的 nodeName 永远是 #document <strong>二、nodeValue 属性：</strong>节点的值 1. 元素节点的 nodeValue 是 undefined 或 null 2. 文本节点的 nodeValue 是文本自身 3. 属性节点的 nodeValue 是属性的值 <strong>三、nodeType 属性:</strong> 节点的类型，是只读的。以下常用的几种结点类型: <strong>元素类型 节点类型</strong> 元素 1 属性 2 文本 3 注释 8 文档 9</p>
                  <h2 id="访问子结点childNodes"><a href="#访问子结点childNodes" class="headerlink" title="访问子结点childNodes"></a>访问子结点childNodes</h2>
                  <p>访问选定元素节点下的所有子节点的列表，返回的值可以看作是一个数组，他具有length属性。 <strong>语法：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">elementNode</span><span class="selector-class">.childNodes</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：</strong> 如果选定的节点没有子节点，则该属性返回不包含节点的 NodeList。 <strong>我们来看看下面的代码:</strong> <a href="http://img.mukewang.com/538405fa00010e6c05630357.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/538405fa00010e6c05630357.jpg" alt=""></a> <strong>运行结果:</strong> <strong>IE:</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">UL子节点个数:<span class="number">3</span></span><br><span class="line">节点类型:<span class="number">1</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>其它浏览器:</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">UL子节点个数:<span class="number">7</span></span><br><span class="line">节点类型:<span class="number">3</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意:</strong> 1. IE全系列、firefox、chrome、opera、safari兼容问题 2. 节点之间的空白符，在firefox、chrome、opera、safari浏览器是文本节点，所以IE是3，其它浏览器是7，如下图所示: <a href="http://img.mukewang.com/538d2b8a000163e303430127.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/538d2b8a000163e303430127.jpg" alt=""></a> <strong>如果把代码改成这样:</strong>
                  <ul>
                    <li>javascript</li>
                    <li>jQuery</li>
                    <li>PHP</li>
                  </ul> <strong>运行结果:（IE和其它浏览器结果是一样的）</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">UL子节点个数:<span class="number">3</span></span><br><span class="line">节点类型:<span class="number">1</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="访问子结点的第一和最后项"><a href="#访问子结点的第一和最后项" class="headerlink" title="访问子结点的第一和最后项"></a>访问子结点的第一和最后项</h2>
                  <p>一、<strong><code>firstChild</code></strong> 属性返回‘childNodes’数组的第一个子节点。如果选定的节点没有子节点，则该属性返回 NULL。 <strong>语法：</strong></p>
                  <figure class="highlight crmsh">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">node</span>.<span class="title">firstChild</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>说明：</strong>与elementNode.childNodes[0]是同样的效果。 二、 <strong><code>lastChild</code></strong> 属性返回‘childNodes’数组的最后一个子节点。如果选定的节点没有子节点，则该属性返回 NULL。 <strong>语法：</strong></p>
                  <figure class="highlight crmsh">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">node</span>.<span class="title">lastChild</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>说明：</strong>与elementNode.childNodes[elementNode.childNodes.length-1]是同样的效果。 <strong>注意:</strong> 上一节中，我们知道Internet Explorer 会忽略节点之间生成的空白文本节点，而其它浏览器不会。我们可以通过检测节点类型，过滤子节点。 (以后章节讲解)</p>
                  <h2 id="访问父节点parentNode"><a href="#访问父节点parentNode" class="headerlink" title="访问父节点parentNode"></a>访问父节点parentNode</h2>
                  <p>获取指定节点的父节点 <strong>语法：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">elementNode</span><span class="selector-class">.parentNode</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意:父节点只能有一个。</strong> 看看下面的例子,获取 P 节点的父节点，代码如下:</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"text"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span> <span class="attr">id</span>=<span class="string">"con"</span>&gt;</span> parentNode 获取指点节点的父节点<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mynode= <span class="built_in">document</span>.getElementById(<span class="string">"con"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mynode.**parentNode**.nodeName);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果:</p>
                  <figure class="highlight cal">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">parentNode 获取指点节点的父节点</span><br><span class="line"><span class="keyword">DIV</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>访问祖节点:</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">elementNode</span><span class="selector-class">.parentNode</span><span class="selector-class">.parentNode</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>看看下面的代码:</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"text"</span>&gt;</span>  </span><br><span class="line">  <span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">    parentNode      </span><br><span class="line">    <span class="tag">&lt;<span class="name">span</span> <span class="attr">id</span>=<span class="string">"con"</span>&gt;</span> 获取指点节点的父节点<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mynode= <span class="built_in">document</span>.getElementById(<span class="string">"con"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mynode.**parentNode.parentNode.**nodeName);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果:</p>
                  <figure class="highlight cal">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">parentNode获取指点节点的父节点</span><br><span class="line"><span class="keyword">DIV</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>注意: 浏览器兼容问题，chrome、firefox等浏览器标签之间的空白也算是一个文本节点。</p>
                  <h2 id="访问兄弟节点"><a href="#访问兄弟节点" class="headerlink" title="访问兄弟节点"></a>访问兄弟节点</h2>
                  <ol>
                    <li>nextSibling 属性可返回某个节点之后紧跟的节点（处于同一树层级中）。 <strong>语法：</strong></li>
                  </ol>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">nodeObject</span><span class="selector-class">.nextSibling</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>说明：</strong>如果无此节点，则该属性返回 null。 2. previousSibling 属性可返回某个节点之前紧跟的节点（处于同一树层级中）。 <strong>语法：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">nodeObject</span><span class="selector-class">.previousSibling</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>说明：</strong>如果无此节点，则该属性返回 null。 注意: 两个属性获取的是节点。Internet Explorer 会忽略节点间生成的空白文本节点（例如，换行符号），而其它浏览器不会忽略。 <strong>解决问题方法:</strong> 判断节点nodeType是否为1, 如是为元素节点，跳过。 <a href="http://img.mukewang.com/5386e3c80001c25607010856.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5386e3c80001c25607010856.jpg" alt=""></a> <strong>运行结果:</strong></p>
                  <figure class="highlight makefile">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">LI = javascript</span><br><span class="line"><span class="section">nextsibling: LI = jquery</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="插入节点appendChild"><a href="#插入节点appendChild" class="headerlink" title="插入节点appendChild()"></a>插入节点appendChild()</h2>
                  <p>在指定节点的最后一个子节点列表之后添加一个新的子节点。 <strong>语法:</strong></p>
                  <figure class="highlight stylus">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="function"><span class="title">appendChild</span><span class="params">(newnode)</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数:</strong> newnode：指定追加的节点。 我们来看看，div标签内创建一个新的 P 标签，代码如下: <a href="http://img.mukewang.com/5398fd020001ad4905890193.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5398fd020001ad4905890193.jpg" alt=""></a> <strong>运行结果:</strong></p>
                  <figure class="highlight actionscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">HTML</span><br><span class="line">JavaScript</span><br><span class="line">This <span class="keyword">is</span> a <span class="keyword">new</span> p</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="插入节点insertBefore"><a href="#插入节点insertBefore" class="headerlink" title="插入节点insertBefore()"></a>插入节点insertBefore()</h2>
                  <p>insertBefore() 方法可在已有的子节点前插入一个新的子节点。</p>
                  <p><strong>语法:</strong></p>
                  <p>insertBefore(newnode,node);</p>
                  <p><strong>参数:</strong></p>
                  <p>newnode: 要插入的新节点。</p>
                  <p>node: 指定此节点前插入节点。</p>
                  <p>我们在来看看下面代码，在指定节点前插入节点。</p>
                  <p><a href="http://img.mukewang.com/5395318100010c6806960431.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5395318100010c6806960431.jpg" alt=""></a></p>
                  <p><strong>运行结果:</strong></p>
                  <figure class="highlight actionscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">This <span class="keyword">is</span> a <span class="keyword">new</span> p</span><br><span class="line">JavaScript</span><br><span class="line">HTML</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意:</strong> otest.insertBefore(newnode,node); 也可以改为: otest.insertBefore(newnode,otest.childNodes[0]);</p>
                  <h2 id="删除节点removeChild"><a href="#删除节点removeChild" class="headerlink" title="删除节点removeChild()"></a>删除节点removeChild()</h2>
                  <p>removeChild() 方法从子节点列表中删除某个节点。如删除成功，此方法可返回被删除的节点，如失败，则返回 NULL。 <strong>语法:</strong></p>
                  <figure class="highlight crmsh">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">nodeObject.removeChild(<span class="keyword">node</span><span class="title">)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数:</strong> node ：必需，指定需要删除的节点。 我们来看看下面代码，删除子点。 <a href="http://img.mukewang.com/5399744d000153a306060342.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5399744d000153a306060342.jpg" alt=""></a> <strong>运行结果:</strong></p>
                  <figure class="highlight julia">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">HTML</span></span><br><span class="line">删除节点的内容: javascript</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意:</strong> 把删除的子节点赋值给 x，这个子节点不在DOM树中，但是还存在内存中，可通过 x 操作。 如果要完全删除对象，给 x 赋 null 值，代码如下: <a href="http://img.mukewang.com/539975a800017c8e04790082.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/539975a800017c8e04790082.jpg" alt=""></a></p>
                  <h2 id="替换元素节点replaceChild"><a href="#替换元素节点replaceChild" class="headerlink" title="替换元素节点replaceChild()"></a>替换元素节点replaceChild()</h2>
                  <p>replaceChild 实现子节点(对象)的替换。返回被替换对象的引用。 <strong>语法：</strong></p>
                  <figure class="highlight crmsh">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">node</span>.<span class="title">replaceChild</span> (newnode,oldnew )</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数：</strong> newnode : 必需，用于替换 oldnew 的对象。 oldnew : 必需，被 newnode 替换的对象。 我们来看看下面的代码: <a href="http://img.mukewang.com/539557d70001c3ee07190429.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/539557d70001c3ee07190429.jpg" alt=""></a> 效果: 将文档中的 Java 改为 JavaScript。 <strong>注意: </strong> 1. 当 oldnode 被替换时，所有与之相关的属性内容都将被移除。 2. newnode 必须先被建立。</p>
                  <h2 id="创建元素节点createElement"><a href="#创建元素节点createElement" class="headerlink" title="创建元素节点createElement"></a>创建元素节点createElement</h2>
                  <p>createElement()方法可创建元素节点。此方法可返回一个 Element 对象。 <strong>语法：</strong></p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">document.create<span class="constructor">Element(<span class="params">tagName</span>)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数:</strong> tagName：字符串值，这个字符串用来指明创建元素的类型。 <strong>注意：</strong>要与appendChild() 或 insertBefore()方法联合使用，将元素显示在页面中。 我们来创建一个按钮，代码如下：</p>
                  <figure class="highlight stata">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;script <span class="keyword">type</span>=<span class="string">"text/javascript"</span>&gt;</span><br><span class="line">   <span class="keyword">var</span> body = document.body; </span><br><span class="line">   <span class="keyword">var</span> <span class="keyword">input</span> = document.createElement(<span class="string">"input"</span>);  </span><br><span class="line">   <span class="keyword">input</span>.<span class="keyword">type</span> = <span class="string">"button"</span>;  </span><br><span class="line">   <span class="keyword">input</span>.value = <span class="string">"创建一个按钮"</span>;  </span><br><span class="line">   body.appendChild(<span class="keyword">input</span>);  </span><br><span class="line"> &lt;/script&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>效果：在HTML文档中，创建一个按钮。 我们也可以使用setAttribute来设置属性，代码如下：</p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;script <span class="keyword">type</span>=<span class="string">"text/javascript"</span>&gt;  </span><br><span class="line">   var body= document.body;             </span><br><span class="line">   var btn = document.create<span class="constructor">Element(<span class="string">"input"</span>)</span>;  </span><br><span class="line">   btn.set<span class="constructor">Attribute(<span class="string">"type"</span>, <span class="string">"text"</span>)</span>;  </span><br><span class="line">   btn.set<span class="constructor">Attribute(<span class="string">"name"</span>, <span class="string">"q"</span>)</span>;  </span><br><span class="line">   btn.set<span class="constructor">Attribute(<span class="string">"value"</span>, <span class="string">"使用setAttribute"</span>)</span>;  </span><br><span class="line">   btn.set<span class="constructor">Attribute(<span class="string">"onclick"</span>, <span class="string">"javascript:alert('This is a text!');"</span>)</span>;       </span><br><span class="line">   body.append<span class="constructor">Child(<span class="params">btn</span>)</span>;  </span><br><span class="line">&lt;/script&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>效果：在HTML文档中，创建一个文本框，使用setAttribute设置属性值。 当点击这个文本框时，会弹出对话框“This is a text!”。</p>
                  <h2 id="创建文本节点createTextNode"><a href="#创建文本节点createTextNode" class="headerlink" title="创建文本节点createTextNode"></a>创建文本节点createTextNode</h2>
                  <p>createTextNode() 方法创建新的文本节点，返回新创建的 Text 节点。 <strong>语法：</strong></p>
                  <figure class="highlight haskell">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="title">document</span>.createTextNode(<span class="class"><span class="keyword">data</span>)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数：</strong> data : 字符串值，可规定此节点的文本。 我们来创建一个
                  <div>元素并向其中添加一条消息，代码如下： <a href="http://img.mukewang.com/53951c200001d32d07130554.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53951c200001d32d07130554.jpg" alt=""></a> <strong>运行结果:</strong> <a href="http://img.mukewang.com/53951c720001996d04080225.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53951c720001996d04080225.jpg" alt=""></a></p>
                    <h2 id="浏览器窗口可视区域大小"><a href="#浏览器窗口可视区域大小" class="headerlink" title="浏览器窗口可视区域大小"></a>浏览器窗口可视区域大小</h2>
                    <p>获得浏览器窗口的尺寸（浏览器的视口，不包括工具栏和滚动条）的方法:</p>
                    <p><strong>一、对于IE9+、Chrome、Firefox、Opera 以及 Safari：</strong></p>
                    <p>• window.innerHeight - 浏览器窗口的内部高度</p>
                    <p>• window.innerWidth - 浏览器窗口的内部宽度</p>
                    <p><strong>二、对于 Internet Explorer 8、7、6、5：</strong></p>
                    <p>• document.documentElement.clientHeight表示HTML文档所在窗口的当前高度。</p>
                    <p>• document.documentElement.clientWidth表示HTML文档所在窗口的当前宽度。</p>
                    <p>或者</p>
                    <p>Document对象的body属性对应HTML文档的

                      <body>标签
                    </p>
                    <p>• document.body.clientHeight</p>
                    <p>• document.body.clientWidth</p>
                    <p><strong>在不同浏览器都实用的 JavaScript 方案：</strong></p>
                    <figure class="highlight dart">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="keyword">var</span> w= <span class="built_in">document</span>.documentElement.clientWidth</span><br><span class="line">      || <span class="built_in">document</span>.body.clientWidth;</span><br><span class="line"><span class="keyword">var</span> h= <span class="built_in">document</span>.documentElement.clientHeight</span><br><span class="line">      || <span class="built_in">document</span>.body.clientHeight;</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <h2 id="网页尺寸scrollHeight"><a href="#网页尺寸scrollHeight" class="headerlink" title="网页尺寸scrollHeight"></a>网页尺寸scrollHeight</h2>
                    <p>scrollHeight和scrollWidth，获取网页内容高度和宽度(不包括滚动条)。 <strong>一、针对IE、Opera:</strong></p>
                    <p>scrollHeight 是网页内容实际高度，可以小于 clientHeight。</p>
                    <p><strong>二、针对NS、FF:</strong></p>
                    <p>scrollHeight 是网页内容高度，不过最小值是 clientHeight。也就是说网页内容实际高度小于 clientHeight 时，scrollHeight 返回 clientHeight 。</p>
                    <p><strong>三、浏览器兼容性</strong></p>
                    <figure class="highlight dart">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="keyword">var</span> w=<span class="built_in">document</span>.documentElement.scrollWidth</span><br><span class="line">   || <span class="built_in">document</span>.body.scrollWidth;</span><br><span class="line"><span class="keyword">var</span> h=<span class="built_in">document</span>.documentElement.scrollHeight</span><br><span class="line">   || <span class="built_in">document</span>.body.scrollHeight;</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p><strong>注意:区分大小写</strong> scrollHeight和scrollWidth还可获取Dom元素中内容实际占用的高度和宽度。</p>
                    <h2 id="网页尺寸offsetHeight"><a href="#网页尺寸offsetHeight" class="headerlink" title="网页尺寸offsetHeight"></a>网页尺寸offsetHeight</h2>
                    <p>offsetHeight和offsetWidth，获取网页内容高度和宽度(包括滚动条等边线，会随窗口的显示大小改变)。</p>
                    <p><strong>一、值</strong></p>
                    <p>offsetHeight = clientHeight + 滚动条 + 边框。</p>
                    <p><strong>二、浏览器兼容性</strong></p>
                    <figure class="highlight dart">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="keyword">var</span> w= <span class="built_in">document</span>.documentElement.offsetWidth</span><br><span class="line">    || <span class="built_in">document</span>.body.offsetWidth;</span><br><span class="line"><span class="keyword">var</span> h= <span class="built_in">document</span>.documentElement.offsetHeight</span><br><span class="line">    || <span class="built_in">document</span>.body.offsetHeight;</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <h2 id="网页卷去的距离与偏移量"><a href="#网页卷去的距离与偏移量" class="headerlink" title="网页卷去的距离与偏移量"></a>网页卷去的距离与偏移量</h2>
                    <p><strong>我们先来看看下面的图：</strong> <a href="http://img.mukewang.com/5347b2b10001e1a307520686.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5347b2b10001e1a307520686.jpg" alt=""></a> <strong>scrollLeft:</strong>设置或获取位于给定对象左边界与窗口中目前可见内容的最左端之间的距离 ，即左边灰色的内容。 <strong>scrollTop:</strong>设置或获取位于对象最顶端与窗口中可见内容的最顶端之间的距离 ，即上边灰色的内容。 <strong>offsetLeft:</strong>获取指定对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置 。 <strong>offsetTop:</strong>获取指定对象相对于版面或由 offsetParent 属性指定的父坐标的计算顶端位置 。 <strong>注意:</strong> <strong>1. 区分大小写</strong> <strong>2. offsetParent：布局中设置postion属性(Relative、Absolute、fixed)的父容器，从最近的父节点开始，一层层向上找，直到HTML的body。</strong></p>
                    <p>来源：<a href="http://www.imooc.com/" target="_blank" rel="noopener">慕课网</a></p>
                    </p>
                  </div>
                </div>
                <div class="post-meta">
                  <span class="post-meta-item">
                    <span class="post-meta-item-icon">
                      <i class="far fa-user"></i>
                    </span>
                    <span class="post-meta-item-text">作者</span>
                    <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                  </span>
                  <span class="post-meta-item">
                    <span class="post-meta-item-icon">
                      <i class="far fa-calendar"></i>
                    </span>
                    <span class="post-meta-item-text">发表于</span>
                    <time title="创建时间：2015-03-08 16:06:48" itemprop="dateCreated datePublished" datetime="2015-03-08T16:06:48+08:00">2015-03-08</time>
                  </span>
                  <span id="/1278.html" class="post-meta-item leancloud_visitors" data-flag-title="JavaScript高级用法四之DOM对象" title="阅读次数">
                    <span class="post-meta-item-icon">
                      <i class="fa fa-eye"></i>
                    </span>
                    <span class="post-meta-item-text">阅读次数：</span>
                    <span class="leancloud-visitors-count"></span>
                  </span>
                  <span class="post-meta-item" title="本文字数">
                    <span class="post-meta-item-icon">
                      <i class="far fa-file-word"></i>
                    </span>
                    <span class="post-meta-item-text">本文字数：</span>
                    <span>8.2k</span>
                  </span>
                  <span class="post-meta-item" title="阅读时长">
                    <span class="post-meta-item-icon">
                      <i class="far fa-clock"></i>
                    </span>
                    <span class="post-meta-item-text">阅读时长 &asymp;</span>
                    <span>7 分钟</span>
                  </span>
                </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1263.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> JavaScript <i class="label-arrow"></i>
                  </a>
                  <a href="/1263.html" class="post-title-link" itemprop="url">JavaScript高级用法三之浏览器对象</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <h2 id="综述"><a href="#综述" class="headerlink" title="综述"></a>综述</h2>
                  <p>本篇的主要内容来自慕课网，内置对象，主要内容如下</p>
                  <ul>
                    <li>1 window对象</li>
                    <li>2 JavaScript 计时器</li>
                    <li>3 计时器setInterval()</li>
                    <li>4 取消计时器clearInterval()</li>
                    <li>5 计时器setTimeout()</li>
                    <li>6 取消计时器clearTimeout()</li>
                    <li>7 History 对象</li>
                    <li>8 返回前一个浏览的页面</li>
                    <li>9 返回下一个浏览的页面</li>
                    <li>10 返回浏览历史中的其他页面</li>
                    <li>11 Location对象</li>
                    <li>12 Navigator对象</li>
                    <li>13 userAgent</li>
                    <li>14 screen对象</li>
                    <li>15 屏幕分辨率的高和宽</li>
                    <li>16 屏幕可用高和宽度</li>
                  </ul>
                  <h2 id="window对象"><a href="#window对象" class="headerlink" title="window对象"></a>window对象</h2>
                  <p>window对象是BOM的核心，window对象指当前的浏览器窗口。 <strong>window对象方法:</strong> <strong><a href="http://img.mukewang.com/535483720001a54506670563.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/535483720001a54506670563.jpg" alt=""></a></strong></p>
                  <h2 id="JavaScript-计时器"><a href="#JavaScript-计时器" class="headerlink" title="JavaScript 计时器"></a>JavaScript 计时器</h2>
                  <p>在JavaScript中，我们可以在设定的时间间隔之后来执行代码，而不是在函数被调用后立即执行。 <strong>计时器类型：</strong> 一次性计时器：仅在指定的延迟时间之后触发一次。 间隔性触发计时器：每隔一定的时间间隔就触发一次。 <strong>计时器方法：</strong> <a href="http://img.mukewang.com/534b35410001d7bc04090143.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/534b35410001d7bc04090143.jpg" alt=""></a></p>
                  <h2 id="计时器setInterval"><a href="#计时器setInterval" class="headerlink" title="计时器setInterval()"></a>计时器setInterval()</h2>
                  <p>在执行时,从载入页面后每隔指定的时间执行代码。 <strong>语法:</strong></p>
                  <figure class="highlight jboss-cli">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">set</span>Interval<span class="params">(代码,交互时间)</span>;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong> 1. 代码：要调用的函数或要执行的代码串。 2. 交互时间：周期性执行或调用表达式之间的时间间隔，以毫秒计（1s=1000ms）。 <strong>返回值:</strong> 一个可以传递给 clearInterval() 从而取消对”代码”的周期性执行的值。 <strong>调用函数格式(</strong>假设有一个clock()函数<strong>):</strong></p>
                  <figure class="highlight stylus">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="function"><span class="title">setInterval</span><span class="params">(<span class="string">"clock()"</span>,<span class="number">1000</span>)</span></span></span><br><span class="line">或</span><br><span class="line"><span class="function"><span class="title">setInterval</span><span class="params">(clock,<span class="number">1000</span>)</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>我们设置一个计时器，每隔100毫秒调用clock()函数，并将时间显示出来，<strong>代码如下:</strong></p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">HTML</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"Content-Type"</span> <span class="attr">content</span>=<span class="string">"text/html; charset=utf-8"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">title</span>&gt;</span>计时器<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> int=setInterval(clock, <span class="number">100</span>)</span></span><br><span class="line"><span class="actionscript">  <span class="function"><span class="keyword">function</span> <span class="title">clock</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> time=<span class="keyword">new</span> <span class="built_in">Date</span>();</span></span><br><span class="line"><span class="javascript">    <span class="built_in">document</span>.getElementById(<span class="string">"clock"</span>).value = time;</span></span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">form</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">id</span>=<span class="string">"clock"</span> <span class="attr">size</span>=<span class="string">"50"</span>  /&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="取消计时器clearInterval"><a href="#取消计时器clearInterval" class="headerlink" title="取消计时器clearInterval()"></a>取消计时器clearInterval()</h2>
                  <p>clearInterval() 方法可取消由 setInterval() 设置的交互时间。</p>
                  <p><strong>语法：</strong></p>
                  <figure class="highlight stylus">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="function"><span class="title">clearInterval</span><span class="params">(id_of_setInterval)</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明:</strong> id_of_setInterval：由 setInterval() 返回的 ID 值。 每隔 100 毫秒调用 clock() 函数,并显示时间。当点击按钮时，停止时间,代码如下:</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">HTML</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"Content-Type"</span> <span class="attr">content</span>=<span class="string">"text/html; charset=utf-8"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">title</span>&gt;</span>计时器<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">   <span class="function"><span class="keyword">function</span> <span class="title">clock</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript">      <span class="keyword">var</span> time=<span class="keyword">new</span> <span class="built_in">Date</span>();                     </span></span><br><span class="line"><span class="javascript">      <span class="built_in">document</span>.getElementById(<span class="string">"clock"</span>).value = time;</span></span><br><span class="line">   &#125;</span><br><span class="line"><span class="actionscript"><span class="comment">// 每隔100毫秒调用clock函数，并将返回值赋值给i</span></span></span><br><span class="line"><span class="actionscript">     <span class="keyword">var</span> i=setInterval(<span class="string">"clock()"</span>,<span class="number">100</span>);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">form</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">id</span>=<span class="string">"clock"</span> <span class="attr">size</span>=<span class="string">"50"</span>  /&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">value</span>=<span class="string">"Stop"</span> <span class="attr">onclick</span>=<span class="string">"clearInterval(i)"</span>  /&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="计时器setTimeout"><a href="#计时器setTimeout" class="headerlink" title="计时器setTimeout()"></a>计时器setTimeout()</h2>
                  <p>setTimeout()计时器，在载入后延迟指定时间后,去执行一次表达式,仅执行一次。</p>
                  <p><strong>语法:</strong></p>
                  <figure class="highlight arduino">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">setTimeout</span>(代码,延迟时间);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong> 1. 要调用的函数或要执行的代码串。 2. 延时时间：在执行代码前需等待的时间，以毫秒为单位（1s=1000ms)。 当我们打开网页3秒后，在弹出一个提示框，<strong>代码如下:</strong></p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">HTML</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">  setTimeout(<span class="string">"alert('Hello!')"</span>, <span class="number">3000</span> );</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>当按钮start被点击时，setTimeout()调用函数，在5秒后弹出一个提示框。</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">HTML</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript"><span class="function"><span class="keyword">function</span> <span class="title">tinfo</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> t=setTimeout(<span class="string">"alert('Hello!')"</span>,<span class="number">5000</span>);</span></span><br><span class="line"> &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">value</span>=<span class="string">"start"</span> <span class="attr">onClick</span>=<span class="string">"tinfo()"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>要创建一个运行于无穷循环中的计数器，我们需要编写一个函数来调用其自身。在下面的代码，当按钮被点击后，输入域便从0开始计数。</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">HTML</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript"><span class="keyword">var</span> num=<span class="number">0</span>;</span></span><br><span class="line"><span class="actionscript"><span class="function"><span class="keyword">function</span> <span class="title">numCount</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript"> <span class="built_in">document</span>.getElementById(<span class="string">'txt'</span>).value=num;</span></span><br><span class="line"> num=num+1;</span><br><span class="line"><span class="actionscript"> setTimeout(<span class="string">"numCount()"</span>,<span class="number">1000</span>);</span></span><br><span class="line"> &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">id</span>=<span class="string">"txt"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">value</span>=<span class="string">"Start"</span> <span class="attr">onClick</span>=<span class="string">"numCount()"</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="取消计时器clearTimeout"><a href="#取消计时器clearTimeout" class="headerlink" title="取消计时器clearTimeout()"></a>取消计时器clearTimeout()</h2>
                  <p>setTimeout()和clearTimeout()一起使用，停止计时器。</p>
                  <p><strong>语法:</strong></p>
                  <figure class="highlight stylus">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="function"><span class="title">clearTimeout</span><span class="params">(id_of_setTimeout)</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明:</strong> <strong>id_of_setTimeout：</strong>由 setTimeout() 返回的 ID 值。该值标识要取消的延迟执行代码块。 下面的例子和上节的无穷循环的例子相似。唯一不同是，现在我们添加了一个 “Stop” 按钮来停止这个计数器：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">HTML</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> num=<span class="number">0</span>,i;</span></span><br><span class="line"><span class="actionscript">  <span class="function"><span class="keyword">function</span> <span class="title">timedCount</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="javascript">    <span class="built_in">document</span>.getElementById(<span class="string">'txt'</span>).value=num;</span></span><br><span class="line">    num=num+1;</span><br><span class="line">    i=setTimeout(timedCount,1000);</span><br><span class="line">  &#125;</span><br><span class="line">    setTimeout(timedCount,1000);</span><br><span class="line"><span class="actionscript">  <span class="function"><span class="keyword">function</span> <span class="title">stopCount</span><span class="params">()</span></span>&#123;</span></span><br><span class="line">    clearTimeout(i);</span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">form</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">id</span>=<span class="string">"txt"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">value</span>=<span class="string">"Stop"</span> <span class="attr">onClick</span>=<span class="string">"stopCount()"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="History-对象"><a href="#History-对象" class="headerlink" title="History 对象"></a>History 对象</h2>
                  <p>history对象记录了用户曾经浏览过的页面(URL)，并可以实现浏览器前进与后退相似导航的功能。 <strong>注意:从**</strong>窗口<strong>被打开的那一刻开始记录，每个浏览器窗口、每个标签页乃至每个框架，都有自己的history对象与特定的window对象关联。 </strong>语法：**</p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span>.<span class="selector-attr">[属性|方法]</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：</strong>window可以省略。 <strong>History 对象属性</strong> <a href="http://img.mukewang.com/53548c030001759e05840068.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53548c030001759e05840068.jpg" alt=""></a> <strong>History 对象方法</strong> <strong><a href="http://img.mukewang.com/53548c200001228206210123.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53548c200001228206210123.jpg" alt=""></a></strong> 使用length属性，当前窗口的浏览历史总长度，<strong>代码如下：</strong></p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> HL = <span class="built_in">window</span>.history.length;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(HL);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="返回前一个浏览的页面"><a href="#返回前一个浏览的页面" class="headerlink" title="返回前一个浏览的页面"></a>返回前一个浏览的页面</h2>
                  <p>back()方法，加载 history 列表中的前一个 URL。 <strong>语法：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span><span class="selector-class">.back</span>();</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>比如，返回前一个浏览的页面，<strong>代码如下：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span><span class="selector-class">.back</span>();</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：等同于点击浏览器的倒退按钮。</strong> back()相当于go(-1),<strong>代码如下:</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span><span class="selector-class">.go</span>(<span class="selector-tag">-1</span>);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="返回下一个浏览的页面"><a href="#返回下一个浏览的页面" class="headerlink" title="返回下一个浏览的页面"></a>返回下一个浏览的页面</h2>
                  <p>forward()方法，加载 history 列表中的下一个 URL。 如果倒退之后，再想回到倒退之前浏览的页面，则可以使用forward()方法,<strong>代码如下:</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span><span class="selector-class">.forward</span>();</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：等价点击前进按钮。</strong> forward()相当于go(1),<strong>代码如下:</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span><span class="selector-class">.go</span>(1);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="返回浏览历史中的其他页面"><a href="#返回浏览历史中的其他页面" class="headerlink" title="返回浏览历史中的其他页面"></a>返回浏览历史中的其他页面</h2>
                  <p>go()方法，根据当前所处的页面，加载 history 列表中的某个具体的页面。 <strong>语法：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span><span class="selector-class">.go</span>(<span class="selector-tag">number</span>);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数：</strong> <a href="http://img.mukewang.com/5354947e00011a9a06490153.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5354947e00011a9a06490153.jpg" alt=""></a> 浏览器中，返回当前页面之前浏览过的第二个历史页面，<strong>代码如下：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span><span class="selector-class">.go</span>(<span class="selector-tag">-2</span>);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：和在浏览器中单击两次后退按钮操作一样。</strong> 同理，返回当前页面之后浏览过的第三个历史页面，<strong>代码如下：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span><span class="selector-class">.go</span>(3);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="Location对象"><a href="#Location对象" class="headerlink" title="Location对象"></a>Location对象</h2>
                  <p>location用于获取或设置窗体的URL，并且可以用于解析URL。 <strong>语法:</strong></p>
                  <figure class="highlight 1c">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">location.[属性<span class="string">|方法]</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>location对象属性图示:</strong> <a href="http://img.mukewang.com/53605c5a0001b26909900216.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53605c5a0001b26909900216.jpg" alt=""></a> <strong>location 对象属性：</strong> <strong><a href="http://img.mukewang.com/5354b1d00001c4ec06220271.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5354b1d00001c4ec06220271.jpg" alt=""></a></strong> <strong>location 对象方法:</strong> <strong><a href="http://img.mukewang.com/5354b1eb00016a2405170126.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5354b1eb00016a2405170126.jpg" alt=""></a></strong></p>
                  <h2 id="Navigator对象"><a href="#Navigator对象" class="headerlink" title="Navigator对象"></a>Navigator对象</h2>
                  <p>Navigator 对象包含有关浏览器的信息，通常用于检测浏览器与操作系统的版本。 <strong>对象属性:</strong> <a href="http://img.mukewang.com/5354cff70001428b06880190.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5354cff70001428b06880190.jpg" alt=""></a> 查看浏览器的名称和版本，<strong>代码如下:</strong></p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">   <span class="keyword">var</span> browser=navigator.appName;</span></span><br><span class="line"><span class="actionscript">   <span class="keyword">var</span> b_version=navigator.appVersion;</span></span><br><span class="line"><span class="javascript">   <span class="built_in">document</span>.write(<span class="string">"Browser name"</span>+browser);</span></span><br><span class="line"><span class="javascript">   <span class="built_in">document</span>.write(<span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">   <span class="built_in">document</span>.write(<span class="string">"Browser version"</span>+b_version);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="userAgent"><a href="#userAgent" class="headerlink" title="userAgent"></a>userAgent</h2>
                  <p>返回用户代理头的字符串表示(就是包括浏览器版本信息等的字符串) <strong>语法</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">navigator</span><span class="selector-class">.userAgent</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>几种浏览的user_agent.，像360的兼容模式用的是IE、极速模式用的是chrom的内核。 <a href="http://img.mukewang.com/535a3a4a0001e03f06870189.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/535a3a4a0001e03f06870189.jpg" alt=""></a> 使用userAgent判断使用的是什么浏览器(假设使用的是IE8浏览器),<strong>代码如下:</strong></p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">function validB()&#123; </span><br><span class="line">  var u_agent = navigator.userAgent; </span><br><span class="line">  var <span class="attribute">B_name</span>=<span class="string">"Failed to identify the browser"</span>; </span><br><span class="line">  <span class="keyword">if</span>(u_agent.indexOf(<span class="string">"Firefox"</span>)&gt;-1)&#123; </span><br><span class="line">      <span class="attribute">B_name</span>=<span class="string">"Firefox"</span>; </span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(u_agent.indexOf(<span class="string">"Chrome"</span>)&gt;-1)&#123; </span><br><span class="line">      <span class="attribute">B_name</span>=<span class="string">"Chrome"</span>; </span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(u_agent.indexOf(<span class="string">"MSIE"</span>)&gt;-1&amp;&amp;u_agent.indexOf(<span class="string">"Trident"</span>)&gt;-1)&#123; </span><br><span class="line">      <span class="attribute">B_name</span>=<span class="string">"IE(8-10)"</span>;  </span><br><span class="line">  &#125;</span><br><span class="line">    document.write(<span class="string">"B_name:"</span>+B_name+<span class="string">"&lt;br&gt;"</span>);</span><br><span class="line">    document.write(<span class="string">"u_agent:"</span>+u_agent+<span class="string">"&lt;br&gt;"</span>); </span><br><span class="line">&#125;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果:</strong> <a href="http://img.mukewang.com/535dea1e00017b0b06880265.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/535dea1e00017b0b06880265.jpg" alt=""></a></p>
                  <h2 id="screen对象"><a href="#screen对象" class="headerlink" title="screen对象"></a>screen对象</h2>
                  <p>screen对象用于获取用户的屏幕信息。 <strong>语法：</strong></p>
                  <figure class="highlight coffeescript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">window</span>.screen.属性</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>对象属性:</strong> <strong><a href="http://img.mukewang.com/5354d2810001a47706210213.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5354d2810001a47706210213.jpg" alt=""></a></strong></p>
                  <h2 id="屏幕分辨率的高和宽"><a href="#屏幕分辨率的高和宽" class="headerlink" title="屏幕分辨率的高和宽"></a>屏幕分辨率的高和宽</h2>
                  <p>window.screen 对象包含有关用户屏幕的信息。 1. screen.height 返回屏幕分辨率的高 2. screen.width 返回屏幕分辨率的宽 <strong>注意:</strong> 1.单位以像素计。 2. window.screen 对象在编写时可以不使用 window 这个前缀。 我们来获取屏幕的高和宽，代码如下:</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write( <span class="string">"屏幕宽度："</span>+screen.width+<span class="string">"px&lt;br /&gt;"</span> );</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write( <span class="string">"屏幕高度："</span>+screen.height+<span class="string">"px&lt;br /&gt;"</span> );</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="屏幕可用高和宽度"><a href="#屏幕可用高和宽度" class="headerlink" title="屏幕可用高和宽度"></a>屏幕可用高和宽度</h2>
                  <p>1. screen.availWidth 属性返回访问者屏幕的宽度，以像素计，减去界面特性，比如任务栏。 2. screen.availHeight 属性返回访问者屏幕的高度，以像素计，减去界面特性，比如任务栏。 <strong>注意:</strong> 不同系统的任务栏默认高度不一样，及任务栏的位置可在屏幕上下左右任何位置，所以有可能可用宽度和高度不一样。 我们来获取屏幕的可用高和宽度，<strong>代码如下：</strong></p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="built_in">document</span>.write(<span class="string">"可用宽度："</span> + screen.availWidth);</span></span><br><span class="line"><span class="javascript"><span class="built_in">document</span>.write(<span class="string">"可用高度："</span> + screen.availHeight);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意:根据屏幕的不同显示值不同。</strong></p>
                  <p>来源：<a href="http://www.imooc.com/" target="_blank" rel="noopener">慕课网</a></p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-03-07 22:41:25" itemprop="dateCreated datePublished" datetime="2015-03-07T22:41:25+08:00">2015-03-07</time>
                </span>
                <span id="/1263.html" class="post-meta-item leancloud_visitors" data-flag-title="JavaScript高级用法三之浏览器对象" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>6.4k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>6 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1257.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> JavaScript <i class="label-arrow"></i>
                  </a>
                  <a href="/1257.html" class="post-title-link" itemprop="url">JavaScript高级用法二之内置对象</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <h2 id="综述"><a href="#综述" class="headerlink" title="综述"></a>综述</h2>
                  <p>本篇的主要内容来自慕课网，内置对象，主要内容如下</p>
                  <ul>
                    <li>1 什么是对象</li>
                    <li>2 Date 日期对象</li>
                    <li>3 返回/设置年份方法</li>
                    <li>4 返回星期方法</li>
                    <li>5 返回/设置时间方法</li>
                    <li>6 String 字符串对象</li>
                    <li>7 返回指定位置的字符</li>
                    <li>8 返回指定的字符串首次出现的位置</li>
                    <li>9 字符串分割split()</li>
                    <li>10 提取字符串substring()</li>
                    <li>11 提取指定数目的字符substr()</li>
                    <li>12 Math对象</li>
                    <li>13 向上取整ceil()</li>
                    <li>14 向下取整floor()</li>
                    <li>15 四舍五入round()</li>
                    <li>16 随机数 random()</li>
                    <li>17 Array 数组对象</li>
                    <li>18 数组连接concat()</li>
                    <li>19 指定分隔符连接数组元素join()</li>
                    <li>20 颠倒数组元素顺序reverse()</li>
                    <li>21 选定元素slice()</li>
                    <li>22 数组排序sort()</li>
                  </ul>
                  <h2 id="什么是对象"><a href="#什么是对象" class="headerlink" title="什么是对象"></a>什么是对象</h2>
                  <p>JavaScript 中的所有事物都是对象，如:字符串、数值、数组、函数等，每个对象带有<strong>属性</strong>和<strong>方法</strong>。 <strong>对象的属性：</strong>反映该对象某些特定的性质的，如：字符串的长度、图像的长宽等； <strong>对象的方法：</strong>能够在对象上执行的动作。例如，表单的“提交”(Submit)，时间的“获取”(getYear)等； JavaScript 提供多个内建对象，比如 String、Date、Array 等等，使用对象前先定义，如下使用数组对象：</p>
                  <figure class="highlight haxe">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">  <span class="keyword">var</span> objectName =<span class="keyword">new</span> <span class="type">Array</span>();<span class="comment">//使用new关键字定义对象</span></span><br><span class="line">**或者**</span><br><span class="line">  <span class="keyword">var</span> objectName =[];</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>访问对象属性的语法:</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">objectName</span><span class="selector-class">.propertyName</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>如使用 Array 对象的 length 属性来获得数组的长度：</p>
                  <figure class="highlight haxe">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span> myarray=<span class="keyword">new</span> <span class="type">Array</span>(<span class="number">6</span>);<span class="comment">//定义数组对象</span></span><br><span class="line"><span class="keyword">var</span> myl=myarray.length;<span class="comment">//访问数组长度length属性</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>以上代码执行后，myl的值将是：6</strong> <strong>访问对象的方法：</strong></p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">objectName.<span class="keyword">method</span><span class="constructor">Name()</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>如使用string 对象的 toUpperCase() 方法来将文本转换为大写：</p>
                  <figure class="highlight actionscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span> mystr=<span class="string">"Hello world!"</span>;<span class="comment">//创建一个字符串</span></span><br><span class="line"><span class="keyword">var</span> request=mystr.toUpperCase(); <span class="comment">//使用字符串对象方法</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>以上代码执行后，request的值是<strong>：HELLO WORLD!</strong></p>
                  <h2 id="Date-日期对象"><a href="#Date-日期对象" class="headerlink" title="Date 日期对象"></a>Date 日期对象</h2>
                  <p>日期对象可以储存任意一个日期，并且可以精确到毫秒数（1/1000 秒）。 定义一个时间对象 :</p>
                  <figure class="highlight arcade">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span> Udate=<span class="keyword">new</span> <span class="built_in">Date</span>();</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意**</strong>:**使用关键字new，Date()的首字母必须大写。</p>
                  <p>使 Udate 成为日期对象，并且已有初始值：<strong>当前时间(当前电脑系统时间)</strong>。</p>
                  <p>如果要自定义初始值，可以用以下方法：</p>
                  <figure class="highlight arcade">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span> d = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">2012</span>, <span class="number">10</span>, <span class="number">1</span>);  <span class="comment">//2012年10月1日</span></span><br><span class="line"><span class="keyword">var</span> d = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'Oct 1, 2012'</span>); <span class="comment">//2012年10月1日</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>我们最好使用下面介绍的“方法”来严格定义时间。</p>
                  <p><strong>访问方法语法：</strong>“&lt;日期对象&gt;.&lt;方法&gt;”</p>
                  <p>Date对象中处理时间和日期的常用方法：</p>
                  <p><a href="http://img.mukewang.com/53d1c6ed000151aa04190327.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53d1c6ed000151aa04190327.jpg" alt=""></a></p>
                  <h2 id="返回-设置年份方法"><a href="#返回-设置年份方法" class="headerlink" title="返回/设置年份方法"></a>返回/设置年份方法</h2>
                  <p><strong><code>get/setFullYear()</code></strong> 返回/设置年份，用四位数表示。</p>
                  <figure class="highlight javascript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span> mydate=<span class="keyword">new</span> <span class="built_in">Date</span>();<span class="comment">//当前时间2014年3月6日</span></span><br><span class="line"><span class="built_in">document</span>.write(mydate+<span class="string">"&lt;br&gt;"</span>);<span class="comment">//输出当前时间</span></span><br><span class="line"><span class="built_in">document</span>.write(mydate.getFullYear()+<span class="string">"&lt;br&gt;"</span>);<span class="comment">//输出当前年份</span></span><br><span class="line">mydate.setFullYear(<span class="number">81</span>); <span class="comment">//设置年份</span></span><br><span class="line"><span class="built_in">document</span>.write(mydate+<span class="string">"&lt;br&gt;"</span>); <span class="comment">//输出年份被设定为 0081年。</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意:</strong>不同浏览器， mydate.setFullYear(81)结果不同，年份被设定为 0081或81两种情况。 <strong>结果:</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">Thu Mar <span class="number">06</span> <span class="number">2014</span> <span class="number">10</span>:<span class="number">57</span>:<span class="number">47</span> GMT+<span class="number">0800</span></span><br><span class="line"><span class="number">2014</span></span><br><span class="line">Thu Mar <span class="number">06</span> <span class="number">0081</span> <span class="number">10</span>:<span class="number">57</span>:<span class="number">47</span> GMT+<span class="number">0800</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意:</strong> 1.结果格式依次为：星期、月、日、年、时、分、秒、时区。(火狐浏览器) 2. 不同浏览器，时间格式有差异。</p>
                  <h2 id="返回星期方法"><a href="#返回星期方法" class="headerlink" title="返回星期方法"></a>返回星期方法</h2>
                  <p><strong>getDay()</strong> 返回星期，返回的是0-6的数字，0 表示星期天。如果要返回相对应“星期”，通过数组完成，代码如下:</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mydate=<span class="keyword">new</span> <span class="built_in">Date</span>();<span class="comment">//定义日期对象</span></span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> weekday=[<span class="string">"星期日"</span>,<span class="string">"星期一"</span>,<span class="string">"星期二"</span>,<span class="string">"星期三"</span>,<span class="string">"星期四"</span>,<span class="string">"星期五"</span>,<span class="string">"星期六"</span>];</span></span><br><span class="line"><span class="actionscript"><span class="comment">//定义数组对象,给每个数组项赋值</span></span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> mynum=mydate.getDay();<span class="comment">//返回值存储在变量mynum中</span></span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mydate.getDay());<span class="comment">//输出getDay()获取值</span></span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="string">"今天是："</span>+ weekday[mynum]);<span class="comment">//输出星期几</span></span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>注意：以上代码是在2014年3月7日，星期五运行。</p>
                  <p><strong>结果:</strong></p>
                  <p>5</p>
                  <p>今天是：星期五</p>
                  <h2 id="返回-设置时间方法"><a href="#返回-设置时间方法" class="headerlink" title="返回/设置时间方法"></a>返回/设置时间方法</h2>
                  <p><strong>get/setTime()</strong> 返回/设置时间，单位毫秒数，计算从 1970 年 1 月 1 日零时到日期对象所指的日期的毫秒数。</p>
                  <p>如果将目前日期对象的时间推迟1小时，代码如下:</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mydate=<span class="keyword">new</span> <span class="built_in">Date</span>();</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="string">"当前时间："</span>+mydate+<span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line">  mydate.setTime(mydate.getTime() + 60 * 60 * 1000);</span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="string">"推迟一小时时间："</span> + mydate);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>结果:</strong></p>
                  <p>当前时间：Thu Mar 6 11:46:27 UTC+0800 2014</p>
                  <p>推迟一小时时间：Thu Mar 6 12:46:27 UTC+0800 2014</p>
                  <p><strong>注意:</strong>1. 一小时 60 分，一分 60 秒，一秒 1000 毫秒</p>
                  <pre><code>  2. 时间推迟 1 小时,就是: “x.setTime(x.getTime() + 60 * 60 * 1000);”
</code></pre>
                  <h2 id="String-字符串对象"><a href="#String-字符串对象" class="headerlink" title="String 字符串对象"></a>String 字符串对象</h2>
                  <p>在之前的学习中已经使用字符串对象了，定义字符串的方法就是直接赋值。比如：</p>
                  <figure class="highlight actionscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span> mystr = <span class="string">"I love JavaScript!"</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>定义mystr字符串后，我们就可以访问它的属性和方法。</p>
                  <p><strong>访问字符串对象的属性length:</strong></p>
                  <p>stringObject.length; 返回该字符串的长度。</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">var <span class="attribute">mystr</span>=<span class="string">"Hello World!"</span>;</span><br><span class="line">var <span class="attribute">myl</span>=mystr.`length`;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>以上代码执行后，myl 的值将是：12 <strong>访问字符串对象的方法：</strong> 使用 String 对象的 toUpperCase() 方法来将字符串小写字母转换为大写：</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">var <span class="attribute">mystr</span>=<span class="string">"Hello world!"</span>;</span><br><span class="line">var <span class="attribute">mynum</span>=mystr.toUpperCase();</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight erlang-repl">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">以上代码执行后，mynum 的值是：HELLO WORLD!</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="返回指定位置的字符"><a href="#返回指定位置的字符" class="headerlink" title="返回指定位置的字符"></a>返回指定位置的字符</h2>
                  <p>charAt() 方法可返回指定位置的字符。返回的字符是长度为 1 的字符串。</p>
                  <p><strong>语法:</strong></p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">stringObject.<span class="built_in">char</span><span class="constructor">At(<span class="params">index</span>)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong></p>
                  <p><a href="http://img.mukewang.com/53251a310001cf1e03370092.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53251a310001cf1e03370092.jpg" alt=""></a> <strong>注意**</strong>：**1.字符串中第一个字符的下标是 0。最后一个字符的下标为字符串长度减一（string.length-1）。</p>
                  <p>2.如果参数 index 不在 0 与 string.length-1 之间，该方法将返回一个空字符串。</p>
                  <p><strong>如:</strong>在字符串 “I love JavaScript!” 中，返回位置2的字符：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> mystr=<span class="string">"I love JavaScript!"</span></span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mystr.charAt(<span class="number">2</span>));</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：</strong>一个空格也算一个字符。</p>
                  <p>以上代码的运行结果：</p>
                  <figure class="highlight ebnf">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="attribute">l</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="返回指定的字符串首次出现的位置"><a href="#返回指定的字符串首次出现的位置" class="headerlink" title="返回指定的字符串首次出现的位置"></a>返回指定的字符串首次出现的位置</h2>
                  <p>indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。</p>
                  <p><strong>语法</strong></p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">stringObject.index<span class="constructor">Of(<span class="params">substring</span>, <span class="params">startpos</span>)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong></p>
                  <p><a href="http://img.mukewang.com/53853d4200019feb04920149.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53853d4200019feb04920149.jpg" alt=""></a> <strong>说明：</strong></p>
                  <p>1.该方法将从头到尾地检索字符串 stringObject，看它是否含有子串 substring。</p>
                  <p>2.可选参数，从stringObject的startpos位置开始查找substring，如果没有此参数将从stringObject的开始位置查找。</p>
                  <p>3.如果找到一个 substring，则返回 substring 的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。</p>
                  <p><strong>注意：</strong>1.indexOf() 方法区分大小写。</p>
                  <p>2.如果要检索的字符串值没有出现，则该方法返回 -1。</p>
                  <p>例如: 对 “I love JavaScript!” 字符串内进行不同的检索：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> str=<span class="string">"I love JavaScript!"</span></span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(str.indexOf(<span class="string">"I"</span>) + <span class="string">"&lt;br /&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(str.indexOf(<span class="string">"v"</span>) + <span class="string">"&lt;br /&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(str.indexOf(<span class="string">"v"</span>,<span class="number">8</span>));</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>以上代码的输出：</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">0</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">9</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="字符串分割split"><a href="#字符串分割split" class="headerlink" title="字符串分割split()"></a>字符串分割split()</h2>
                  <p><strong>知识讲解：</strong> split() 方法将字符串分割为字符串数组，并返回此数组。</p>
                  <h3 id="语法："><a href="#语法：" class="headerlink" title="语法："></a><strong>语法：</strong></h3>
                  <figure class="highlight maxima">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">stringObject.<span class="built_in">split</span>(separator,<span class="built_in">limit</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="参数说明"><a href="#参数说明" class="headerlink" title="参数说明:"></a><strong>参数说明:</strong></h3>
                  <p><strong><a href="http://img.mukewang.com/532bee4800014c0404230108.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/532bee4800014c0404230108.jpg" alt=""></a></strong> <strong>注意：</strong>如果把空字符串 (“”) 用作 separator，那么 stringObject 中的每个字符之间都会被分割。 <strong>我们将按照不同的方式来分割字符串：</strong> 使用指定符号分割字符串，代码如下:</p>
                  <figure class="highlight dart">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span> mystr = <span class="string">"www.imooc.com"</span>;</span><br><span class="line"><span class="built_in">document</span>.write(mystr.split(<span class="string">"."</span>)+<span class="string">"&lt;br&gt;"</span>);</span><br><span class="line"><span class="built_in">document</span>.write(mystr.split(<span class="string">"."</span>, <span class="number">2</span>)+<span class="string">"&lt;br&gt;"</span>);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果:</strong></p>
                  <figure class="highlight autohotkey">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">www,</span>imooc,com</span><br><span class="line"><span class="built_in">www,</span>imooc</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>将字符串分割为字符，代码如下：</p>
                  <figure class="highlight applescript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">document.<span class="built_in">write</span>(mystr.split(<span class="string">""</span>)+<span class="string">"&lt;br&gt;"</span>);</span><br><span class="line">document.<span class="built_in">write</span>(mystr.split(<span class="string">""</span>, <span class="number">5</span>));</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果:</p>
                  <figure class="highlight autohotkey">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">w,</span>w,w,.,i,m,o,o,c,.,c,o,m</span><br><span class="line"><span class="built_in">w,</span>w,w,.,i</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="提取字符串substring"><a href="#提取字符串substring" class="headerlink" title="提取字符串substring()"></a>提取字符串substring()</h2>
                  <p>substring() 方法用于提取字符串中介于两个指定下标之间的字符。 <strong>语法:</strong></p>
                  <figure class="highlight pf">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">stringObject.substring(starP<span class="keyword">os</span>,stopP<span class="keyword">os</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明:</strong> <img src="http://img.mukewang.com/532bf1bb000151af04450082.jpg" alt=""> <strong>注意：</strong> 1. 返回的内容是从 start开始(包含start位置的字符)到 stop-1 处的所有字符，其长度为 stop 减start。 2. 如果参数 start 与 stop 相等，那么该方法返回的就是一个空串（即长度为 0 的字符串）。 3. 如果 start 比 stop 大，那么该方法在提取子串之前会先交换这两个参数。 使用 substring() 从字符串中提取字符串，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> mystr=<span class="string">"I love JavaScript"</span>;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mystr.substring(<span class="number">7</span>));</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mystr.substring(<span class="number">2</span>,<span class="number">6</span>));</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果**</strong>:**</p>
                  <figure class="highlight ebnf">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="attribute">JavaScript</span></span><br><span class="line"><span class="attribute">love</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="提取指定数目的字符substr"><a href="#提取指定数目的字符substr" class="headerlink" title="提取指定数目的字符substr()"></a>提取指定数目的字符substr()</h2>
                  <p>substr() 方法从字符串中提取从 startPos位置开始的指定数目的字符串。 <strong>语法:</strong></p>
                  <figure class="highlight sas">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">stringObject<span class="meta">.substr(</span>startPos,<span class="meta">length</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明:</strong> <a href="http://img.mukewang.com/532bf2e00001105305100098.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/532bf2e00001105305100098.jpg" alt=""></a> <strong>注意：</strong>如果参数startPos是负数，从字符串的尾部开始算起的位置。也就是说，-1 指字符串中最后一个字符，-2 指倒数第二个字符，以此类推。 如果startPos为负数且绝对值大于字符串长度，startPos为0。 使用 substr() 从字符串中提取一些字符，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> mystr=<span class="string">"I love JavaScript!"</span>;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mystr.substr(<span class="number">7</span>));</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mystr.substr(<span class="number">2</span>,<span class="number">4</span>));</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight erlang-repl">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">JavaScript!</span><br><span class="line">love</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="Math对象"><a href="#Math对象" class="headerlink" title="Math对象"></a>Math对象</h2>
                  <p>Math对象，提供对数据的数学计算。 使用 Math 的属性和方法，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mypi=<span class="built_in">Math</span>.PI; </span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> myabs=<span class="built_in">Math</span>.abs(<span class="number">-15</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mypi);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myabs);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果**</strong>:**</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">3.141592653589793</span></span><br><span class="line"><span class="number">15</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：</strong>Math 对象是一个固有的对象，无需创建它，直接把 Math 作为对象使用就可以调用其所有属性和方法。这是它与Date,String对象的区别。 Math 对象属性 <a href="http://img.mukewang.com/532fe7cf0001e7b505170269.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/532fe7cf0001e7b505170269.jpg" alt=""></a> Math 对象方法 <a href="http://img.mukewang.com/532fe841000174db05160622.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/532fe841000174db05160622.jpg" alt=""></a> 以上方法不做全部讲解，只讲解部分方法。</p>
                  <h2 id="向上取整ceil"><a href="#向上取整ceil" class="headerlink" title="向上取整ceil()"></a>向上取整ceil()</h2>
                  <p>ceil() 方法可对一个数进行向上取整。 <strong>语法:</strong></p>
                  <figure class="highlight gml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">Math.<span class="built_in">ceil</span>(<span class="symbol">x</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明:</strong> <a href="http://img.mukewang.com/532fe8e00001e4e605230063.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/532fe8e00001e4e605230063.jpg" alt=""></a> <strong>注意：</strong>它返回的是大于或等于x，并且与x最接近的整数。 我们将把 ceil() 方法运用到不同的数字上，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.ceil(<span class="number">0.8</span>) + <span class="string">"&lt;br /&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.ceil(<span class="number">6.3</span>) + <span class="string">"&lt;br /&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.ceil(<span class="number">5</span>) + <span class="string">"&lt;br /&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.ceil(<span class="number">3.5</span>) + <span class="string">"&lt;br /&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.ceil(<span class="number">-5.1</span>) + <span class="string">"&lt;br /&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.ceil(<span class="number">-5.9</span>))</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">7</span></span><br><span class="line"><span class="number">5</span></span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="number">-5</span></span><br><span class="line"><span class="number">-5</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="向下取整floor"><a href="#向下取整floor" class="headerlink" title="向下取整floor()"></a>向下取整floor()</h2>
                  <p>floor() 方法可对一个数进行向下取整。 <strong>语法:</strong></p>
                  <figure class="highlight gml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">Math.<span class="built_in">floor</span>(<span class="symbol">x</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong> <img src="http://img.mukewang.com/532fea54000194c604380058.jpg" alt=""> <strong>注意：</strong>返回的是小于或等于x，并且与x最接近的整数。 我们将在不同的数字上使用 floor() 方法，代码如下:</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.floor(<span class="number">0.8</span>)+ <span class="string">"&lt;br&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.floor(<span class="number">6.3</span>)+ <span class="string">"&lt;br&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.floor(<span class="number">5</span>)+ <span class="string">"&lt;br&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.floor(<span class="number">3.5</span>)+ <span class="string">"&lt;br&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.floor(<span class="number">-5.1</span>)+ <span class="string">"&lt;br&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.floor(<span class="number">-5.9</span>))</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">0</span></span><br><span class="line"><span class="number">6</span></span><br><span class="line"><span class="number">5</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="number">-6</span></span><br><span class="line"><span class="number">-6</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="四舍五入round"><a href="#四舍五入round" class="headerlink" title="四舍五入round()"></a>四舍五入round()</h2>
                  <p>round() 方法可把一个数字四舍五入为最接近的整数。 <strong>语法:</strong></p>
                  <figure class="highlight gml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">Math.<span class="built_in">round</span>(<span class="symbol">x</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong> <img src="http://img.mukewang.com/532feb70000180ab03210059.jpg" alt=""> <strong>注意：</strong> 1. 返回与 x 最接近的整数。 2. 对于 0.5，该方法将进行上舍入。(5.5 将舍入为 6) 3. 如果 x 与两侧整数同等接近，则结果接近 +∞方向的数字值 。(如 -5.5 将舍入为 -5; -5.52 将舍入为 -6),如下图: <a href="http://img.mukewang.com/53fc4cc8000169a907530196.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53fc4cc8000169a907530196.jpg" alt=""></a> 把不同的数舍入为最接近的整数,代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="string">`Math.round(1.6)`</span>+ <span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="string">`Math.round(2.5)`</span>+ <span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="string">`Math.round(0.49)`</span>+ <span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="string">`Math.round(-6.4)`</span>+ <span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="string">`Math.round(-6.6)`</span>);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">2</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="number">0</span></span><br><span class="line"><span class="number">-6</span></span><br><span class="line"><span class="number">-7</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="随机数-random"><a href="#随机数-random" class="headerlink" title="随机数 random()"></a>随机数 random()</h2>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">random() 方法可返回介于 <span class="number">0</span> ~ <span class="number">1</span>（大于或等于 <span class="number">0</span> 但小于 <span class="number">1</span> )之间的一个随机数。</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>语法：</strong></p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="module-access"><span class="module"><span class="identifier">Math</span>.</span></span>random<span class="literal">()</span>;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：</strong>返回一个大于或等于 0 但小于 1 的符号为正的数字值。 我们取得介于 0 到 1 之间的一个随机数，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(<span class="built_in">Math</span>.random());</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">0.190305486195328</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意**</strong>:**因为是随机数，所以每次运行结果不一样，但是0 ~ 1的数值。</p>
                  <p>获得0 ~ 10之间的随机数，代码如下:</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write((<span class="built_in">Math</span>.random())*<span class="number">10</span>);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">8.72153625893887</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="Array-数组对象"><a href="#Array-数组对象" class="headerlink" title="Array 数组对象"></a>Array 数组对象</h2>
                  <p>数组对象是一个对象的集合，里边的对象可以是不同类型的。数组的每一个成员对象都有一个“下标”，用来表示它在数组中的位置，是从零开始的 <strong>数组定义的方法：</strong> 1. 定义了一个空数组:</p>
                  <figure class="highlight haxe">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span>  数组名= <span class="keyword">new</span> <span class="type">Array</span>();</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>2. 定义时指定有n个空元素的数组：</p>
                  <figure class="highlight haxe">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">var</span> 数组名 =<span class="keyword">new</span> <span class="type">Array</span>(n);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>3.定义数组的时候，直接初始化数据：</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">var  数组名 = [&lt;元素<span class="number">1</span>&gt;, &lt;元素<span class="number">2</span>&gt;, &lt;元素<span class="number">3</span>&gt;...];</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>我们定义myArray数组，并赋值，<strong>代码如下：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">var myArray = [<span class="number">2</span>, <span class="number">8</span>, <span class="number">6</span>];</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>说明：</strong>定义了一个数组 myArray，里边的元素是：myArray[0] = 2; myArray[1] = 8; myArray[2] = 6。 <strong>数组元素使用：</strong></p>
                  <figure class="highlight abnf">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">数组名[下标] = 值<span class="comment">;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意</strong>: 数组的下标用方括号括起来，从0开始。</p>
                  <p><strong>数组属性：</strong></p>
                  <p>length 用法：&lt;数组对象&gt;.length；返回：数组的长度，即数组里有多少个元素。它等于数组里最后一个元素的下标加一。 <strong>数组方法：</strong> <a href="http://img.mukewang.com/533295ab0001dead05190599.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/533295ab0001dead05190599.jpg" alt=""></a></p>
                  <h2 id="数组连接concat"><a href="#数组连接concat" class="headerlink" title="数组连接concat()"></a>数组连接concat()</h2>
                  <p>concat() 方法用于连接两个或多个数组。此方法返回一个新数组，不改变原来的数组。 <strong>语法</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">array</span>Object.concat(<span class="built_in">array</span>1,<span class="built_in">array</span>2,...,<span class="built_in">array</span>N)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong></p>
                  <p><strong><img src="http://img.mukewang.com/5332968d0001d39b05010137.jpg" alt=""></strong></p>
                  <p><strong>注意:</strong> 该方法不会改变现有的数组，而仅仅会返回被连接数组的一个副本。</p>
                  <p>我们创建一个数组，将把 concat() 中的参数连接到数组 myarr 中，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mya = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>);</span></span><br><span class="line"><span class="actionscript">  mya[<span class="number">0</span>] = <span class="string">"1"</span>;</span></span><br><span class="line"><span class="actionscript">  mya[<span class="number">1</span>] = <span class="string">"2"</span>;</span></span><br><span class="line"><span class="actionscript">  mya[<span class="number">2</span>] = <span class="string">"3"</span>;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mya.concat(<span class="number">4</span>,<span class="number">5</span>)+<span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mya); </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span></span><br><span class="line"><span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>我们创建了三个数组，然后使用 concat() 把它们连接起来，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mya1= <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="string">"hello!"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mya2= <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="string">"I"</span>,<span class="string">"love"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> mya3= <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="string">"JavaScript"</span>,<span class="string">"!"</span>);</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">var</span> mya4=mya1.concat(mya2,mya3);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(mya4);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight erlang-repl">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">hello!,I,love,JavaScript,!</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="指定分隔符连接数组元素join"><a href="#指定分隔符连接数组元素join" class="headerlink" title="指定分隔符连接数组元素join()"></a>指定分隔符连接数组元素join()</h2>
                  <p>join()方法用于把数组中的所有元素放入一个字符串。元素是通过指定的分隔符进行分隔的。 <strong>语法：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">array</span>Object.join(分隔符)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明:</strong></p>
                  <p><img src="http://img.mukewang.com/533297ff0001516905150059.jpg" alt=""> 注意：返回一个字符串，该字符串把数组中的各个元素串起来，用&lt;分隔符&gt;置于元素与元素之间。这个方法不影响数组原本的内容。 我们使用join（）方法，将数组的所有元素放入一个字符串中，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> myarr = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>);</span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">0</span>] = <span class="string">"I"</span>;</span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">1</span>] = <span class="string">"love"</span>;</span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">2</span>] = <span class="string">"JavaScript"</span>;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr.join());</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight autohotkey">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">I,</span>love,JavaScript</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>我们将使用分隔符来分隔数组中的元素，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> myarr = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>)</span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">0</span>] = <span class="string">"I"</span>;</span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">1</span>] = <span class="string">"love"</span>;</span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">2</span>] = <span class="string">"JavaScript"</span>;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr.join(<span class="string">"."</span>));</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">I</span><span class="selector-class">.love</span><span class="selector-class">.JavaScript</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="颠倒数组元素顺序reverse"><a href="#颠倒数组元素顺序reverse" class="headerlink" title="颠倒数组元素顺序reverse()"></a>颠倒数组元素顺序reverse()</h2>
                  <p>reverse() 方法用于颠倒数组中元素的顺序。</p>
                  <p><strong>语法：</strong></p>
                  <figure class="highlight ada">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">arrayObject.<span class="keyword">reverse</span>()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意：</strong>该方法会改变原来的数组，而不会创建新的数组。 定义数组myarr并赋值，然后颠倒其元素的顺序：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> myarr = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>)</span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">0</span>] = <span class="string">"1"</span></span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">1</span>] = <span class="string">"2"</span></span></span><br><span class="line"><span class="actionscript">  myarr[<span class="number">2</span>] = <span class="string">"3"</span></span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr + <span class="string">"&lt;br /&gt;"</span>)</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(my<span class="string">`arr.reverse()`</span>)</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span></span><br><span class="line"><span class="number">3</span>,<span class="number">2</span>,<span class="number">1</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="选定元素slice"><a href="#选定元素slice" class="headerlink" title="选定元素slice()"></a>选定元素slice()</h2>
                  <p>slice() 方法可从已有的数组中返回选定的元素。 <strong>语法</strong></p>
                  <figure class="highlight pgsql">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">arrayObject.<span class="keyword">slice</span>(<span class="keyword">start</span>,<span class="keyword">end</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong> <a href="http://img.mukewang.com/533299680001637b05160145.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/533299680001637b05160145.jpg" alt=""></a> 1.返回一个新的数组，包含从 start 到 end （不包括该元素）的 arrayObject 中的元素。 2. 该方法并不会修改数组，而是返回一个子数组。 <strong>注意：</strong> 1. 可使用负值从数组的尾部选取元素。 2.如果 end 未被规定，那么 slice() 方法会选取从 start 到数组结尾的所有元素。 3. String.slice() 与 Array.slice() 相似。 我们将创建一个新数组，然后从其中选取的元素，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> myarr = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr + <span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr.slice(<span class="number">2</span>,<span class="number">4</span>) + <span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span></span><br><span class="line"><span class="number">3</span>,<span class="number">4</span></span><br><span class="line"><span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="数组排序sort"><a href="#数组排序sort" class="headerlink" title="数组排序sort()"></a>数组排序sort()</h2>
                  <p><strong>sort()</strong>方法使数组中的元素按照一定的顺序排列。</p>
                  <p><strong>语法:</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">array</span>Object.sort(方法函数)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>参数说明：</strong> <img src="http://img.mukewang.com/53329a2a000127f705170060.jpg" alt=""></p>
                  <p>1.如果不指定&lt;方法函数&gt;，则按unicode码顺序排列。</p>
                  <p>2.如果指定&lt;方法函数&gt;，则按&lt;方法函数&gt;所指定的排序方法排序。</p>
                  <figure class="highlight abnf">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">myArray.sort(sortMethod)<span class="comment">;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>使用sort()将数组进行排序，代码如下：</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> myarr1 = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="string">"Hello"</span>,<span class="string">"John"</span>,<span class="string">"love"</span>,<span class="string">"JavaScript"</span>); </span></span><br><span class="line"><span class="javascript">  <span class="keyword">var</span> myarr2 = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="string">"80"</span>,<span class="string">"16"</span>,<span class="string">"50"</span>,<span class="string">"6"</span>,<span class="string">"100"</span>,<span class="string">"1"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr1.sort()+<span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr2.sort());</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">Hello,JavaScript,John,love</span><br><span class="line"><span class="number">1</span>,<span class="number">100</span>,<span class="number">16</span>,<span class="number">50</span>,<span class="number">6</span>,<span class="number">80</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>注意:上面的代码没有按照数值的大小对数字进行排序。</strong> <strong>如要实现这一点，就必须使用一个排序函数，代码如下：</strong></p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">  <span class="function"><span class="keyword">function</span> <span class="title">sortNum</span><span class="params">(a,b)</span> </span>&#123;</span></span><br><span class="line"><span class="actionscript">  <span class="keyword">return</span> a - b;</span></span><br><span class="line"><span class="actionscript"> <span class="comment">//升序，如降序，把“a - b”该成“b - a”</span></span></span><br><span class="line">&#125;</span><br><span class="line"><span class="javascript"> <span class="keyword">var</span> myarr = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="string">"80"</span>,<span class="string">"16"</span>,<span class="string">"50"</span>,<span class="string">"6"</span>,<span class="string">"100"</span>,<span class="string">"1"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr + <span class="string">"&lt;br&gt;"</span>);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">document</span>.write(myarr.sort(sortNum));</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><strong>运行结果：</strong></p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">80</span>,<span class="number">16</span>,<span class="number">50</span>,<span class="number">6</span>,<span class="number">100</span>,<span class="number">1</span></span><br><span class="line"><span class="number">1</span>,<span class="number">6</span>,<span class="number">16</span>,<span class="number">50</span>,<span class="number">80</span>,<span class="number">100</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>来源：<a href="http://www.imooc.com/" target="_blank" rel="noopener">慕课网</a></p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-03-07 22:32:16" itemprop="dateCreated datePublished" datetime="2015-03-07T22:32:16+08:00">2015-03-07</time>
                </span>
                <span id="/1257.html" class="post-meta-item leancloud_visitors" data-flag-title="JavaScript高级用法二之内置对象" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>10k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>9 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1253.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> JavaScript <i class="label-arrow"></i>
                  </a>
                  <a href="/1253.html" class="post-title-link" itemprop="url">JavaScript高级用法一之事件响应与网页交互</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <h2 id="综述"><a href="#综述" class="headerlink" title="综述"></a>综述</h2>
                  <p>本篇的主要内容来自慕课网，事件响应与网页交互，主要内容如下</p>
                  <ul>
                    <li>1 什么是事件</li>
                    <li>2 鼠标单击事件( onclick ）</li>
                    <li>3 鼠标经过事件（onmouseover）</li>
                    <li>4 鼠标移开事件（onmouseout）</li>
                    <li>5 光标聚焦事件（onfocus）</li>
                    <li>6 失焦事件（onblur）</li>
                    <li>7 内容选中事件（onselect）</li>
                    <li>8 文本框内容改变事件（onchange）</li>
                    <li>9 加载事件（onload）</li>
                    <li>10 卸载事件（onunload）</li>
                  </ul>
                  <h2 id="什么是事件"><a href="#什么是事件" class="headerlink" title="什么是事件"></a>什么是事件</h2>
                  <p>JavaScript 创建动态页面。事件是可以被 JavaScript 侦测到的行为。 网页中的每个元素都可以产生某些可以触发 JavaScript 函数或程序的事件。</p>
                  <p>比如说，当用户单击按钮或者提交表单数据时，就发生一个鼠标单击（onclick）事件，需要浏览器做出处理，返回给用户一个结果。</p>
                  <p><strong>主要事件表:</strong></p>
                  <p><a href="http://img.mukewang.com/53e198540001b66404860353.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53e198540001b66404860353.jpg" alt=""></a></p>
                  <h2 id="鼠标单击事件-onclick-）"><a href="#鼠标单击事件-onclick-）" class="headerlink" title="鼠标单击事件( onclick ）"></a>鼠标单击事件( onclick ）</h2>
                  <p>onclick是鼠标单击事件，当在网页上单击鼠标时，就会发生该事件。同时onclick事件调用的程序块就会被执行，通常与按钮一起使用。 比如，我们单击按钮时，触发 onclick 事件，并调用两个数和的函数add2()。代码如下：</p>
                  <figure class="highlight xquery">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="xml">   </span><span class="xml"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span></span><br><span class="line"><span class="xml">      function add2()</span><span class="xquery">&#123;</span></span><br><span class="line"><span class="xquery">        var numa,numb<span class="built_in">,sum</span>;</span></span><br><span class="line"><span class="xquery">        numa=<span class="number">6</span>;</span></span><br><span class="line"><span class="xquery">        numb=<span class="number">8</span>;</span></span><br><span class="line"><span class="xquery">       <span class="built_in"> sum</span>=numa+numb;</span></span><br><span class="line"><span class="xquery">       <span class="built_in"> document</span>.write(<span class="string">"两数和为:"</span><span class="built_in">+sum</span>);  &#125;</span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="xml">   </span><span class="xml"><span class="tag">&lt;<span class="name">form</span>&gt;</span></span></span><br><span class="line"><span class="xml">      <span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">"button"</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">value</span>=<span class="string">"点击提交"</span> <span class="attr">onclick</span>=<span class="string">"add2()"</span> /&gt;</span></span></span><br><span class="line"><span class="xml">   <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="鼠标经过事件（onmouseover）"><a href="#鼠标经过事件（onmouseover）" class="headerlink" title="鼠标经过事件（onmouseover）"></a>鼠标经过事件（onmouseover）</h2>
                  <p>鼠标经过事件，当鼠标移到一个对象上时，该对象就触发onmouseover事件，并执行onmouseover事件调用的程序。 现实鼠标经过”确定”按钮时，触发onmouseover事件，调用函数info()，弹出消息框，代码如下: <a href="http://img.mukewang.com/53e196e500013f1807700354.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53e196e500013f1807700354.jpg" alt=""></a> <strong>运行结果:</strong> <img src="http://img.mukewang.com/53e196fd00017d8704870416.jpg" alt=""></p>
                  <h2 id="鼠标移开事件（onmouseout）"><a href="#鼠标移开事件（onmouseout）" class="headerlink" title="鼠标移开事件（onmouseout）"></a>鼠标移开事件（onmouseout）</h2>
                  <p>鼠标移开事件，当鼠标移开当前对象时，执行onmouseout调用的程序。</p>
                  <p>当把鼠标移动到”登录”按钮上，然后再移开时，触发onmouseout事件，调用函数message()，代码如下:</p>
                  <p><a href="http://img.mukewang.com/53e195580001a0bc07730356.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53e195580001a0bc07730356.jpg" alt=""></a></p>
                  <p><strong>运行结果:</strong> <a href="http://img.mukewang.com/53e195bf00010d1804760385.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53e195bf00010d1804760385.jpg" alt=""></a></p>
                  <h2 id="光标聚焦事件（onfocus）"><a href="#光标聚焦事件（onfocus）" class="headerlink" title="光标聚焦事件（onfocus）"></a>光标聚焦事件（onfocus）</h2>
                  <p>当网页中的对象获得聚点时，执行onfocus调用的程序就会被执行。 如下代码, 当将光标移到文本框内时，即焦点在文本框内，触发onfocus 事件，并调用函数message()。 <a href="http://img.mukewang.com/53e19337000113d108390338.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53e19337000113d108390338.jpg" alt=""></a> <strong>运行结果：</strong> <a href="http://img.mukewang.com/5312c5660001821a04300326.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5312c5660001821a04300326.jpg" alt=""></a></p>
                  <h2 id="失焦事件（onblur）"><a href="#失焦事件（onblur）" class="headerlink" title="失焦事件（onblur）"></a>失焦事件（onblur）</h2>
                  <p>onblur事件与onfocus是相对事件，当光标离开当前获得聚焦对象的时候，触发onblur事件，同时执行被调用的程序。 如下代码, 网页中有用户和密码两个文本框。当前光标在用户文本框内时（即焦点在文本框），在光标离开该文本框后（即失焦时），触发onblur事件，并调用函数message()。 <a href="http://img.mukewang.com/53e191d00001dfe508560326.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53e191d00001dfe508560326.jpg" alt=""></a> <strong>运行结果：</strong> <strong><a href="http://img.mukewang.com/5312da710001968704410319.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5312da710001968704410319.jpg" alt=""></a></strong> </p>
                  <h2 id="内容选中事件（onselect）"><a href="#内容选中事件（onselect）" class="headerlink" title="内容选中事件（onselect）"></a>内容选中事件（onselect）</h2>
                  <p>选中事件，当文本框或者文本域中的文字被选中时，触发onselect事件，同时调用的程序就会被执行。 如下代码,当选中用户文本框内的文字时，触发onselect 事件，并调用函数message()。 <a href="http://img.mukewang.com/53e190b70001ffa908560325.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/53e190b70001ffa908560325.jpg" alt=""></a> <strong>运行结果：</strong> <strong><a href="http://img.mukewang.com/5312d7ba00013fff03950319.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5312d7ba00013fff03950319.jpg" alt=""></a></strong></p>
                  <h2 id="文本框内容改变事件（onchange）"><a href="#文本框内容改变事件（onchange）" class="headerlink" title="文本框内容改变事件（onchange）"></a>文本框内容改变事件（onchange）</h2>
                  <p>通过改变文本框的内容来触发onchange事件，同时执行被调用的程序。 如下代码,当用户将文本框内的文字改变后，弹出对话框“您改变了文本内容！”。 <a href="http://img.mukewang.com/5312d59c00011cd311490444.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5312d59c00011cd311490444.jpg" alt=""></a> <strong>运行结果：</strong> <strong><a href="http://img.mukewang.com/5312d5c600012c3703960319.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5312d5c600012c3703960319.jpg" alt=""></a></strong></p>
                  <h2 id="加载事件（onload）"><a href="#加载事件（onload）" class="headerlink" title="加载事件（onload）"></a>加载事件（onload）</h2>
                  <p>事件会在页面加载完成后立即发生，同时执行被调用的程序。 注意：1. 加载页面时，触发onload事件，事件写在

                    <body>标签内。 2. 此节的加载页面，可理解为打开一个新页面时。 如下代码,当加载一个新页面时，弹出对话框“加载中，请稍等…”。 <a href="http://img.mukewang.com/5312e3c10001bd9908920372.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5312e3c10001bd9908920372.jpg" alt=""></a> <strong>运行结果：</strong> <strong><a href="http://img.mukewang.com/5312e3eb0001e8a103930318.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5312e3eb0001e8a103930318.jpg" alt=""></a></strong>
                  </p>
                  <h2 id="卸载事件（onunload）"><a href="#卸载事件（onunload）" class="headerlink" title="卸载事件（onunload）"></a>卸载事件（onunload）</h2>
                  <p>当用户退出页面时（页面关闭、页面刷新等），触发onUnload事件，同时执行被调用的程序。</p>
                  <p><strong>注意：不同浏览器对onunload事件支持不同。</strong></p>
                  <p>如下代码,当退出页面时，弹出对话框“您确定离开该网页吗？”。</p>
                  <p><a href="http://img.mukewang.com/5312ee6b0001f89408950418.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/5312ee6b0001f89408950418.jpg" alt=""></a></p>
                  <p><strong>运行结果：（IE浏览器）</strong></p>
                  <p><a href="http://img.mukewang.com/546470c90001583205460464.jpg" target="_blank" rel="noopener"><img src="http://img.mukewang.com/546470c90001583205460464.jpg" alt=""></a></p>
                  <p>来源：<a href="http://www.imooc.com" target="_blank" rel="noopener">慕课网</a></p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-03-07 22:23:24" itemprop="dateCreated datePublished" datetime="2015-03-07T22:23:24+08:00">2015-03-07</time>
                </span>
                <span id="/1253.html" class="post-meta-item leancloud_visitors" data-flag-title="JavaScript高级用法一之事件响应与网页交互" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>1.8k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>2 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1250.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> 个人随笔 <i class="label-arrow"></i>
                  </a>
                  <a href="/1250.html" class="post-title-link" itemprop="url">珍惜自己年轻的时光吧</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>话说书桌比较乱的人比较有创造力？很不幸我的桌面我好像就是这么一个人呐，哈哈哈我开玩笑的~ 一直以来养成了一个定期清理书桌的习惯，在不到那个清理的时间，我会随意摆放自己想要摆放的东西，有时候，我的桌面比较乱也是正常的。这不，今天周六了嘛，整理一下东西吧。三下五除二，桌面回归了它正常的模样。又心想干脆连橱柜一起整理了吧，不差那回事。 橱柜的东西比较多，应该是放假前的时候堆成那个样子了吧，各种衣服窝在一起，随后我找出自己的大皮箱，一点点地整理衣服。整理的时候发现，有多少衣服是我曾经穿过一个冬季或夏季，甚至只穿过一次之后，就将它束之高阁，打入冷宫，再也不去理会。仔细回想起来，这还是我大一的时候的衣服吧，一件件牛仔裤，一件件曾经以为很时尚很Fashion的衬衫、卫衣，现在我却一概不去理会。 上学期，为了参加一个比赛，爸妈给我买了第一套正装，还有领带，皮鞋，还有那亮闪闪的皮带。穿过一次之后，就觉得这样的行头的确不错。比赛回来，我便买了一件比较成熟的衬衫，还有一条黑色长裤，穿上，把衬衫那么一扎，皮带扎在最外面，顿时觉得太有范。后来，不知不觉，我似乎是穿这样的衣服上瘾了么？过年，又入手了双皮鞋，一件酒红色外套。这下，彻底就和之前的打扮相比，像是变了个人。 下午整理衣服，每每整理到一件，我都会回忆起曾经穿着这一身衣服做了什么，去了哪些地方。曾经的生活，现在想想，是那么地美好和自由。虽说现在生活也不差，但似乎觉得，自己失去了什么；也或者，将来的日子，我又会失去什么。是啊，现在都大三了，也不小了，将来的生活也再不会那么无忧无虑，什么事也不用操心。等将来的日子，为了工作，为了应酬，为了会议，自己可能会多么奔波劳累也说不定，那时候，想回归现在的生活，已经是不可能的事了吧！ 至少，现在的我，还算年轻，我还有资本去做自己想做的事。等以后自己独立了，天天西装革履，衬衣领带，再想找回曾经的样子，肯定是已经做不到了。 最后，我换了身行头，刮了刮胡子，再换回这几年的装扮，让自己年轻一把~ 珍惜年轻时候的时光吧~ </p>
                  <p>崔庆才</p>
                  <p>2015/3/7</p>
                  <p>随笔</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-03-07 15:54:24" itemprop="dateCreated datePublished" datetime="2015-03-07T15:54:24+08:00">2015-03-07</time>
                </span>
                <span id="/1250.html" class="post-meta-item leancloud_visitors" data-flag-title="珍惜自己年轻的时光吧" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>857</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>1 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1229.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> PHP <i class="label-arrow"></i>
                  </a>
                  <a href="/1229.html" class="post-title-link" itemprop="url">PHP高级特性二之文件处理</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>PHP中的文件处理也是一个相当重要的模块，这一篇的主要内容就是PHP中文件系统的简介。</p>
                  <h2 id="文件系统用途"><a href="#文件系统用途" class="headerlink" title="文件系统用途"></a>文件系统用途</h2>
                  <p>1. 项目处理都离不开文件处理 2. 可以用文件长时间保存数据 3. 建立缓存，在服务器中进行文件操作</p>
                  <h2 id="文件系统函数用法详述"><a href="#文件系统函数用法详述" class="headerlink" title="文件系统函数用法详述"></a>文件系统函数用法详述</h2>
                  <h3 id="1-基本的判断函数"><a href="#1-基本的判断函数" class="headerlink" title="1.基本的判断函数"></a>1.基本的判断函数</h3>
                  <blockquote>
                    <p><a href="http://php.net/manual/zh/function.is-dir.php" target="_blank" rel="noopener">is_dir</a> — 判断给定文件名是否是一个目录 <a href="http://php.net/manual/zh/function.is-file.php" target="_blank" rel="noopener">is_file</a> — 判断给定文件名是否为一个文件 <a href="http://php.net/manual/zh/function.is-executable.php" target="_blank" rel="noopener">is_executable</a> — 判断给定文件名是否可执行 <a href="http://php.net/manual/zh/function.is-link.php" target="_blank" rel="noopener">is_link</a> — 判断给定文件名是否为一个符号连接 <a href="http://php.net/manual/zh/function.is-readable.php" target="_blank" rel="noopener">is_readable</a> — 判断给定文件名是否可读 <a href="http://php.net/manual/zh/function.is-uploaded-file.php" target="_blank" rel="noopener">is_uploaded_file</a> — 判断文件是否是通过 HTTP POST 上传的 <a href="http://php.net/manual/zh/function.is-writable.php" target="_blank" rel="noopener">is_writable</a> — 判断给定的文件名是否可写 <a href="http://php.net/manual/zh/function.is-writeable.php" target="_blank" rel="noopener">is_writeable</a> — is_writable 的别名</p>
                  </blockquote>
                  <h3 id="2-文件相关信息获取"><a href="#2-文件相关信息获取" class="headerlink" title="2.文件相关信息获取"></a>2.文件相关信息获取</h3>
                  <blockquote>
                    <p><a href="http://php.net/manual/zh/function.file-exists.php" target="_blank" rel="noopener">file_exists</a> — 检查文件或目录是否存在 <a href="http://php.net/manual/zh/function.fileatime.php" target="_blank" rel="noopener">fileatime</a> — 取得文件的上次访问时间 <a href="http://php.net/manual/zh/function.filectime.php" target="_blank" rel="noopener">filectime</a> — 取得文件的 inode 修改时间 <a href="http://php.net/manual/zh/function.filegroup.php" target="_blank" rel="noopener">filegroup</a> — 取得文件的组 <a href="http://php.net/manual/zh/function.fileinode.php" target="_blank" rel="noopener">fileinode</a> — 取得文件的 inode <a href="http://php.net/manual/zh/function.filemtime.php" target="_blank" rel="noopener">filemtime</a> — 取得文件修改时间 <a href="http://php.net/manual/zh/function.fileowner.php" target="_blank" rel="noopener">fileowner</a> — 取得文件的所有者 <a href="http://php.net/manual/zh/function.fileperms.php" target="_blank" rel="noopener">fileperms</a> — 取得文件的权限 <a href="http://php.net/manual/zh/function.filesize.php" target="_blank" rel="noopener">filesize</a> — 取得文件大小 <a href="http://php.net/manual/zh/function.filetype.php" target="_blank" rel="noopener">filetype</a> — 取得文件类型</p>
                  </blockquote>
                  <p>下面我们写一个例子，传入文件名，打印它的详细信息。</p>
                  <figure class="highlight php">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">   <span class="function"><span class="keyword">function</span> <span class="title">getFileInfo</span><span class="params">($filename)</span></span>&#123;</span><br><span class="line">       <span class="keyword">if</span>(!file_exists($filename))&#123;</span><br><span class="line">           <span class="keyword">echo</span> <span class="string">'文件'</span>.($filename).<span class="string">'不存在'</span>;</span><br><span class="line">           <span class="keyword">return</span>;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span>(is_file($filename))&#123;</span><br><span class="line">           <span class="keyword">echo</span> $filename.<span class="string">'是一个文件'</span>;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span>(is_dir($filename))&#123;</span><br><span class="line">           <span class="keyword">echo</span> $filename.<span class="string">'是一个目录'</span>;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span>(is_executable($filename))&#123;</span><br><span class="line">           <span class="keyword">echo</span> $filename.<span class="string">'是可执行文件'</span>;</span><br><span class="line">       &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">           <span class="keyword">echo</span> $filename.<span class="string">'不是可执行文件'</span>;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span>(is_readable($filename))&#123;</span><br><span class="line">           <span class="keyword">echo</span> $filename.<span class="string">'是可读的'</span>;</span><br><span class="line">       &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">           <span class="keyword">echo</span> $filename.<span class="string">'不是可读的'</span>;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span>(is_writable($filename))&#123;</span><br><span class="line">           <span class="keyword">echo</span> $filename.<span class="string">'是可写入的'</span>;</span><br><span class="line">       &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">           <span class="keyword">echo</span> $filename.<span class="string">'不是可写入的'</span>;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">echo</span> <span class="string">'文件'</span>.$filename.<span class="string">'的大小是'</span>.getFileSize(filesize($filename)).<span class="string">''</span>;</span><br><span class="line">       <span class="keyword">echo</span> <span class="string">'文件'</span>.$filename.<span class="string">'的类型是'</span>.filetype($filename).<span class="string">''</span>;</span><br><span class="line">       <span class="keyword">echo</span> <span class="string">'文件'</span>.$filename.<span class="string">'的所有者是'</span>.fileowner($filename).<span class="string">''</span>;</span><br><span class="line">       <span class="keyword">echo</span> <span class="string">'文件'</span>.$filename.<span class="string">'的最后访问时间为'</span>.getTime(fileatime($filename)).<span class="string">''</span>;</span><br><span class="line">       <span class="keyword">echo</span> <span class="string">'文件'</span>.$filename.<span class="string">'的inode是'</span>.fileinode($filename).<span class="string">''</span>;</span><br><span class="line">       <span class="keyword">echo</span> <span class="string">'文件'</span>.$filename.<span class="string">'的修改时间是'</span>.getTime(filemtime($filename)).<span class="string">''</span>;</span><br><span class="line">       <span class="keyword">echo</span> <span class="string">'文件'</span>.$filename.<span class="string">'的权限是'</span>.fileperms($filename).<span class="string">''</span>;</span><br><span class="line">&#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">function</span> <span class="title">getTime</span><span class="params">($time)</span></span>&#123;</span><br><span class="line">       <span class="keyword">return</span> date(<span class="string">'Y-m-d H:i:s'</span>,$time);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">function</span> <span class="title">getFileSize</span><span class="params">($size)</span></span>&#123;</span><br><span class="line">       $dw = <span class="string">'B'</span>;</span><br><span class="line">       <span class="keyword">if</span>($size&gt;=pow(<span class="number">2</span>,<span class="number">40</span>))&#123;</span><br><span class="line">           $size=round($size/pow(<span class="number">2</span>,<span class="number">40</span>),<span class="number">2</span>);</span><br><span class="line">           $dw = <span class="string">'PB'</span>;</span><br><span class="line">       &#125;<span class="keyword">else</span> <span class="keyword">if</span>($size&gt;=pow(<span class="number">2</span>,<span class="number">30</span>))&#123;</span><br><span class="line">           $size=round($size/pow(<span class="number">2</span>,<span class="number">30</span>),<span class="number">2</span>);</span><br><span class="line">           $dw = <span class="string">'TB'</span>;</span><br><span class="line">       &#125;<span class="keyword">else</span> <span class="keyword">if</span>($size&gt;=pow(<span class="number">2</span>,<span class="number">20</span>))&#123;</span><br><span class="line">           $size=round($size/pow(<span class="number">2</span>,<span class="number">20</span>),<span class="number">2</span>);</span><br><span class="line">           $dw = <span class="string">'GB'</span>;</span><br><span class="line">       &#125;<span class="keyword">else</span> <span class="keyword">if</span>($size&gt;=pow(<span class="number">2</span>,<span class="number">10</span>))&#123;</span><br><span class="line">           $size=round($size/pow(<span class="number">2</span>,<span class="number">10</span>),<span class="number">2</span>);</span><br><span class="line">           $dw = <span class="string">'MB'</span>;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> $size.$dw;</span><br><span class="line">   &#125;</span><br><span class="line">   getFileInfo(<span class="string">'1.php'</span>);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果</p>
                  <blockquote>
                    <p>1.php是一个文件 1.php不是可执行文件 1.php是可读的 1.php不是可写入的 文件1.php的大小是2MB 文件1.php的类型是file 文件1.php的所有者是1000 文件1.php的最后访问时间为2015-03-04 12:58:33 文件1.php的inode是536185 文件1.php的修改时间是2015-03-04 12:58:32 文件1.php的权限是33204</p>
                  </blockquote>
                  <h3 id="3-文件路径相关函数"><a href="#3-文件路径相关函数" class="headerlink" title="3.文件路径相关函数"></a>3.文件路径相关函数</h3>
                  <p><strong>相对路径：相对于当前目录的上级和下级目录</strong></p>
                  <blockquote>
                    <p>. 当前目录 .. 上一级目录</p>
                  </blockquote>
                  <p><strong>路径分隔符号</strong></p>
                  <blockquote>
                    <p>linux/Unix “/“ windows “\“ 不管是什么操作系统PHP的目录分割符号都支技 / (Linux)</p>
                  </blockquote>
                  <p><strong>绝对路径：可以指的操作系统的根，也可以指的是存放网站的文档根目录</strong></p>
                  <blockquote>
                    <p>如果是在服务器中执行（通过PHP文件处理函数执行）路径 则 “根”指的就是操作系统的根 如果程序是下载的客户端，再访问服务器中的文件时，只有通过Apache访问，“根”也就指的是文档根目录</p>
                  </blockquote>
                  <p>三个相关函数</p>
                  <blockquote>
                    <p><a href="http://php.net/manual/zh/function.basename.php" target="_blank" rel="noopener">basename</a> — 返回路径中的文件名部分 <a href="http://php.net/manual/zh/function.dirname.php" target="_blank" rel="noopener">dirname</a> — 返回路径中的目录部分 <a href="http://php.net/manual/zh/function.pathinfo.php" target="_blank" rel="noopener">pathinfo</a> — 返回文件路径的信息</p>
                  </blockquote>
                  <p>例如下面的例子</p>
                  <figure class="highlight bash">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">   <span class="variable">$url1</span>=<span class="string">"./aaa/bbb/index.php"</span>;</span><br><span class="line"><span class="variable">$url2</span>=<span class="string">"../www/yyy/login.rar"</span>;</span><br><span class="line"><span class="variable">$url3</span>=<span class="string">"c:/appserv/www/demo.html"</span>;</span><br><span class="line"><span class="variable">$url4</span>=<span class="string">"http://localhost/yyy/www.gif"</span>;</span><br><span class="line"><span class="built_in">echo</span> basename(<span class="variable">$url1</span>);</span><br><span class="line"><span class="built_in">echo</span> basename(<span class="variable">$url2</span>);</span><br><span class="line"><span class="built_in">echo</span> basename(<span class="variable">$url3</span>);</span><br><span class="line"><span class="built_in">echo</span> basename(<span class="variable">$url4</span>);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果</p>
                  <blockquote>
                    <p>index.php login.rar demo.html www.gif</p>
                  </blockquote>
                  <p>可以看出，basename这个函数返回的是文件的名，也就是最后一个项目。 下面我们看一下dirname的用法</p>
                  <figure class="highlight mel">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">   $url1=<span class="string">"./aaa/bbb/index.php"</span>;</span><br><span class="line">$url2=<span class="string">"../www/yyy/login.rar"</span>;</span><br><span class="line">$url3=<span class="string">"c:/appserv/www/demo.html"</span>;</span><br><span class="line">$url4=<span class="string">"http://localhost/yyy/www.gif"</span>;</span><br><span class="line">echo <span class="keyword">dirname</span>(<span class="keyword">dirname</span>($url1));</span><br><span class="line">echo <span class="keyword">dirname</span>($url2);</span><br><span class="line">echo <span class="keyword">dirname</span>($url3);</span><br><span class="line">echo <span class="keyword">dirname</span>($url4);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果</p>
                  <blockquote>
                    <p>./aaa ../www/yyy c:/appserv/www <a href="http://localhost/yyy" target="_blank" rel="noopener">http://localhost/yyy</a></p>
                  </blockquote>
                  <p>可以发现，dirname这个函数可以多层嵌套使用，返回的就是它所在的路径，即除了最后一项之外所有的项。 另外 pathinfo的以上所有信息都可以获取到，另外还包括了文件名和扩展名 比如下面的结果</p>
                  <blockquote>
                    <p>Array ( [dirname] =&gt; ../www/yyy [basename] =&gt; login.rar [extension] =&gt; rar [filename] =&gt; login )</p>
                  </blockquote>
                  <h3 id="4-文件的创建删除修改"><a href="#4-文件的创建删除修改" class="headerlink" title="4. 文件的创建删除修改"></a>4. 文件的创建删除修改</h3>
                  <blockquote>
                    <p><a href="http://php.net/manual/zh/function.touch.php" target="_blank" rel="noopener">touch</a> — 创建一个文件 <a href="http://php.net/manual/zh/function.unlink.php" target="_blank" rel="noopener">unlink</a> — 删除文件 <a href="http://php.net/manual/zh/function.rename.php" target="_blank" rel="noopener">rename</a> — 重命名一个文件或目录 <a href="http://php.net/manual/zh/function.copy.php" target="_blank" rel="noopener">copy</a> — 拷贝文件</p>
                  </blockquote>
                  <p>例如下面的例子</p>
                  <figure class="highlight less">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">touch</span>(<span class="string">"./php.apahce"</span>); <span class="comment">//创建文件</span></span><br><span class="line"><span class="selector-tag">unlink</span>(<span class="string">"C:/AppServ/www/xsphp/apache.php"</span>);  <span class="comment">//删除文件</span></span><br><span class="line"><span class="selector-tag">rename</span>(<span class="string">"./test.txt"</span>, <span class="string">"d:/test2.txt"</span>);    <span class="comment">//重命名文件</span></span><br><span class="line"><span class="selector-tag">copy</span>(<span class="string">"cache.txt"</span>, <span class="string">"./cache5.txt"</span>);   <span class="comment">//复制文件</span></span><br><span class="line"><span class="selector-tag">chmod</span>(<span class="string">"a.txt"</span>,<span class="number">755</span>);   <span class="comment">//设置文件权限</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>权限相关内容</p>
                  <blockquote>
                    <p>rwx 表这个文件的拥有者 r读 w写 x执行 rwx 表这个文件的拥有者所在的组 r读 w写 x执行 rwx 其它用户对这个为文件的权限 r读 w写 x执行</p>
                  </blockquote>
                  <h2 id="文件读写"><a href="#文件读写" class="headerlink" title="文件读写"></a>文件读写</h2>
                  <h3 id="1-file-get-contents-string"><a href="#1-file-get-contents-string" class="headerlink" title="1. file_get_contents(string)"></a>1. file_get_contents(string)</h3>
                  <p>传入文件名，直接得到文件中的文本信息，返回的内容即为文件中的文本。 例如</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span></span></span><br><span class="line"><span class="php"> $str = file_get_contents(<span class="string">"1.txt"</span>);</span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> $str;</span></span><br><span class="line"><span class="php"> <span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>则直接打开了 1.txt 文件中的内容，并返回文件中的文本信息。 如果文件不存在，那么会提示</p>
                  <blockquote>
                    <p><strong>Warning</strong>: file_get_contents(2.txt): failed to open stream: No such file or directory</p>
                  </blockquote>
                  <p>同样，文件还可以是远程文件，例如，参数传入 <a href="http://www.qq.com" target="_blank" rel="noopener">http://www.qq.com</a> 即可以呈现腾讯网的首页内容。 缺点：不能读取指定部分的内容，一次性全部读取。</p>
                  <h3 id="2-file-put-contents-filename-content"><a href="#2-file-put-contents-filename-content" class="headerlink" title="2. file_put_contents(filename,content)"></a>2. file_put_contents(filename,content)</h3>
                  <p>写入文件，filename是写入文件的文件名，content是写入内容，返回值是成功写入的字符长度。</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> file_put_contents(<span class="string">"2.txt"</span>,<span class="string">'abcd'</span>);</span></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>2.txt 文件如果不存在，那么则会创建这个文件并写入 abcd 这个字符串，返回 4 ，为字符串的长度。 如果文件存在，则会将文件清空，然后写入字符串，返回写入长度。 缺点：不能以追加的方式写入文件。</p>
                  <h3 id="3-file-filename"><a href="#3-file-filename" class="headerlink" title="3.file(filename)"></a>3.file(filename)</h3>
                  <p>file是直接打开某一个文件，返回的结果是一个数组，每一行是数组的一个元素。也就是说，获取行数只需要输出数组的大小即可。例如</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"> $str = file(<span class="string">"1.txt"</span>);</span></span><br><span class="line"><span class="php"> var_dump($str);</span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> count($str);</span></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>即可得到数组形式的行内容，而且输出了行数。 缺点：不能读取指定部分的内容。</p>
                  <h3 id="4-fopen-filename-mode"><a href="#4-fopen-filename-mode" class="headerlink" title="4.fopen(filename,mode)"></a>4.fopen(filename,mode)</h3>
                  <p>filename是文件名，可以是路径加名，也可以是远程服务器文件。 mode是打开文件的方式</p>
                  <blockquote>
                    <p>r，以只读模式打开文件 r+，除了读，还可以写入。 w， 以只写的方式打开，如果文件不存在，则创建这个文件,并写放内容，如果文件存在，并原来有内容，则会清除原文件中所有内容，再写入（打开已有的重要文件） w+，除了可以写用fwrite, 还可以读fread a，以只写的方式打开，如果文件不存在，则创建这个文件，并写放内容，如果文件存在，并原来有内容，则不清除原有文件内容，再原有文件内容的最后写入新内容，（追加） a+，除了可以写用fwrite, 还可以读fread b，以二进制模式打开文件（图，电影） t，以文本模式打开文件</p>
                  </blockquote>
                  <p>注意：</p>
                  <blockquote>
                    <p>r+具有读写属性，从文件头开始写，保留原文件中没有被覆盖的内容； w+具有读写属性，写的时候如果文件存在，会被清空，从头开始写。</p>
                  </blockquote>
                  <p>返回的是一个文件资源</p>
                  <h3 id="5-fwrite-file-content"><a href="#5-fwrite-file-content" class="headerlink" title="5.fwrite(file,content)"></a>5.fwrite(file,content)</h3>
                  <p>文件写入功能，file是文件资源，用fopen函数获取来的，content是写入内容。同 fputs 函数。 例如</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"> $file = fopen(<span class="string">"1.txt"</span>,<span class="string">"r+"</span>);</span></span><br><span class="line"><span class="php"> $result = fwrite($file,<span class="string">"xx"</span>);</span></span><br><span class="line"><span class="php"> <span class="keyword">if</span>($result)&#123;</span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> <span class="string">"Success"</span>;</span></span><br><span class="line"><span class="php"> &#125;<span class="keyword">else</span></span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> <span class="string">"Failed"</span>;</span></span><br><span class="line"><span class="php"> &#125;</span></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>则从头开始写入资源，即把前两个字符设为 xx</p>
                  <h3 id="6-fread-file-size"><a href="#6-fread-file-size" class="headerlink" title="6. fread(file,size)"></a>6. fread(file,size)</h3>
                  <p>读取文件指定部分的长度，file是文件资源，由fopen返回的对象，size是读取字符的长度。 例如</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"> $file = fopen(<span class="string">"1.txt"</span>,<span class="string">"r"</span>);</span></span><br><span class="line"><span class="php"> $content = fread($file,filesize(<span class="string">"1.txt"</span>));</span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> $content;</span></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>不过，上述的 filesize 方法只能获取本地文件大小，对于远程文件的读取就要换一种方法了。 例如</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"> $file = fopen(<span class="string">"http://www.qq.com"</span>,<span class="string">"r"</span>);</span></span><br><span class="line"><span class="php"> $str = <span class="string">""</span>;</span></span><br><span class="line"><span class="php"> <span class="keyword">while</span>(!feof($file))&#123;  <span class="comment">//判断时候到了文件结尾</span></span></span><br><span class="line"><span class="php"> $str.=fread($file,<span class="number">1024</span>);</span></span><br><span class="line"><span class="php"> &#125;</span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> $str;</span></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="7-fgets-file"><a href="#7-fgets-file" class="headerlink" title="7.fgets(file)"></a>7.fgets(file)</h3>
                  <p>file是文件资源，每次读取一行。例如我们读取出腾讯首页一共有多少行。</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"> <span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"> $file = fopen(<span class="string">"http://www.qq.com"</span>,<span class="string">"r"</span>);</span></span><br><span class="line"><span class="php"> $str = <span class="string">""</span>;</span></span><br><span class="line"><span class="php"> $count = <span class="number">0</span>;</span></span><br><span class="line"><span class="php"> <span class="keyword">while</span>(!feof($file))&#123;</span></span><br><span class="line"><span class="php"> $str .= fgets($file);</span></span><br><span class="line"><span class="php"> $count ++;</span></span><br><span class="line"><span class="php"> &#125;</span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> $count;</span></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>会输出结果 8893，我们可以查看源文件，看看它一共有多少行，验证一下即可。</p>
                  <h3 id="7-fgetc-file"><a href="#7-fgetc-file" class="headerlink" title="7.fgetc(file)"></a>7.fgetc(file)</h3>
                  <p>与fgets方法很相似，file是文件资源，每次读取个字符。例如我们读取出腾讯首页一共有多少个字符。</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="php"><span class="meta">&lt;?php</span> </span></span><br><span class="line"><span class="php"> $file = fopen(<span class="string">"http://www.qq.com"</span>,<span class="string">"r"</span>);</span></span><br><span class="line"><span class="php"> $str = <span class="string">""</span>;</span></span><br><span class="line"><span class="php"> $count = <span class="number">0</span>;</span></span><br><span class="line"><span class="php"> <span class="keyword">while</span>(!feof($file))&#123;</span></span><br><span class="line"><span class="php"> $str .= fgetc($file);</span></span><br><span class="line"><span class="php"> $count ++;</span></span><br><span class="line"><span class="php"> &#125;</span></span><br><span class="line"><span class="php"> <span class="keyword">echo</span> $count;</span></span><br><span class="line"><span class="php"><span class="meta">?&gt;</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>上述代码便会输出所有的字符数量。</p>
                  <h3 id="8-ftell-file"><a href="#8-ftell-file" class="headerlink" title="8.ftell(file)"></a>8.ftell(file)</h3>
                  <p>ftell 是返回当前读文件的指针位置，file 是文件资源，是由 fopen 返回的对象。</p>
                  <h3 id="9-fseek-file-offset-whence"><a href="#9-fseek-file-offset-whence" class="headerlink" title="9.fseek(file,offset,whence)"></a>9.fseek(file,offset,whence)</h3>
                  <p><strong>file</strong> 文件系统指针，是典型地由 fopen() 创建的 resource(资源)。 <strong>offset</strong> 偏移量。 要移动到文件尾之前的位置，需要给 offset 传递一个负值，并设置 whence 为 SEEK_END。 <strong>whence</strong></p>
                  <blockquote>
                    <p>SEEK_SET - 设定位置等于 offset 字节。 SEEK_CUR - 设定位置为当前位置加上 offset。 SEEK_END - 设定位置为文件尾加上 offset。</p>
                  </blockquote>
                  <h3 id="10-rewind-file"><a href="#10-rewind-file" class="headerlink" title="10.rewind($file)"></a>10.rewind($file)</h3>
                  <p>回到文件头部，file是文件资源 例如</p>
                  <figure class="highlight gams">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;?php </span><br><span class="line"> <span class="symbol">$</span><span class="keyword">file</span> = fopen(<span class="string">"1.txt"</span>,<span class="string">"r"</span>);</span><br><span class="line"> echo ftell(<span class="symbol">$</span><span class="keyword">file</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出读取前的指针位置</span></span><br><span class="line"> echo fread(<span class="symbol">$</span><span class="keyword">file</span>,<span class="number">10</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//读取10个字符，指针移动10个单位</span></span><br><span class="line"> echo ftell(<span class="symbol">$</span><span class="keyword">file</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出读取完之后当前指针位置</span></span><br><span class="line"> fseek(<span class="symbol">$</span><span class="keyword">file</span>,<span class="number">20</span>,SEEK_CUR); <span class="comment">//当前指针前移20单位</span></span><br><span class="line"> echo ftell(<span class="symbol">$</span><span class="keyword">file</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出移动之后指针的位置</span></span><br><span class="line"> echo fread(<span class="symbol">$</span><span class="keyword">file</span>,<span class="number">10</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出读取的10个字符</span></span><br><span class="line"> echo ftell(<span class="symbol">$</span><span class="keyword">file</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出读完10个字符之后指针的位置</span></span><br><span class="line"> fseek(<span class="symbol">$</span><span class="keyword">file</span>,<span class="number">-20</span>,SEEK_END); <span class="comment">//指针移动到文件末尾前20个字符</span></span><br><span class="line"> echo ftell(<span class="symbol">$</span><span class="keyword">file</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出移动之后指针的位置</span></span><br><span class="line"> echo fread(<span class="symbol">$</span><span class="keyword">file</span>,<span class="number">10</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出文件末尾20个字符</span></span><br><span class="line"> echo ftell(<span class="symbol">$</span><span class="keyword">file</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出读完10个字符之后指针的位置</span></span><br><span class="line"> rewind(<span class="symbol">$</span><span class="keyword">file</span>); <span class="comment">//回到文件头部</span></span><br><span class="line"> echo ftell(<span class="symbol">$</span><span class="keyword">file</span>).<span class="string">"&lt;br&gt;"</span>; <span class="comment">//输出移动之后指针的位置</span></span><br><span class="line">?&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果：</p>
                  <blockquote>
                    <p>0 cuiqingcai 10 30 uiqingcai. 40 374 i.comcuiqi 384 0</p>
                  </blockquote>
                  <h3 id="11-flock-file-operation-wouldblock"><a href="#11-flock-file-operation-wouldblock" class="headerlink" title="11.flock(file,operation[,wouldblock])"></a>11.flock(file,operation[,wouldblock])</h3>
                  <p><strong>file</strong> 文件资源指针，是典型地由 fopen() 创建的 resource(资源)。 <strong>operation</strong> operation 可以是以下值之一：</p>
                  <blockquote>
                    <p>LOCK_SH取得共享锁定（读取的程序）。 LOCK_EX 取得独占锁定（写入的程序。 LOCK_UN 释放锁定（无论共享或独占）。</p>
                  </blockquote>
                  <p>如果不希望 flock() 在锁定时堵塞，则是 LOCK_NB（Windows 上还不支持）。 <strong>wouldblock</strong> 如果锁定会堵塞的话（EWOULDBLOCK 错误码情况下），可选的第三个参数会被设置为 TRUE。（Windows 上不支持） 例如</p>
                  <figure class="highlight gams">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;?php </span><br><span class="line"> <span class="symbol">$</span><span class="keyword">file</span> = fopen(<span class="string">"1.txt"</span>,<span class="string">"a"</span>);</span><br><span class="line"> <span class="keyword">if</span>(flock(<span class="symbol">$</span><span class="keyword">file</span>,LOCK_EX))&#123;</span><br><span class="line"> fwrite(<span class="symbol">$</span><span class="keyword">file</span>,<span class="string">"xxx"</span>);</span><br><span class="line"> flock(<span class="symbol">$</span><span class="keyword">file</span>,LOCK_UN);</span><br><span class="line"> &#125;</span><br><span class="line">?&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-03-03 23:54:39" itemprop="dateCreated datePublished" datetime="2015-03-03T23:54:39+08:00">2015-03-03</time>
                </span>
                <span id="/1229.html" class="post-meta-item leancloud_visitors" data-flag-title="PHP高级特性二之文件处理" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>7.2k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>7 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1186.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> PHP <i class="label-arrow"></i>
                  </a>
                  <a href="/1186.html" class="post-title-link" itemprop="url">PHP高级特性一之正则表达式用法</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>在PHP中，我们进行字符串处理时，能用字符串处理函数时我们当然要使用简单的字符串处理函数，但字符串处理函数的能力是有限的，所以我们就需要利用一个更强大的工具，那就是正则表达式。</p>
                  <h2 id="简述正则表达式"><a href="#简述正则表达式" class="headerlink" title="简述正则表达式"></a>简述正则表达式</h2>
                  <h3 id="正则表达式是什么？"><a href="#正则表达式是什么？" class="headerlink" title="正则表达式是什么？"></a>正则表达式是什么？</h3>
                  <blockquote>
                    <p>正则表达式就是描述字符串排列模式的一种自定义语法规则。正则表达式就是通过构建具有特定规则的模式，和输入字符串信息进行比较，然后进行分割、匹配、查找、替换等等的相关操作。正则表达式不是PHP中独有的，多种语言均可以使用正则表达式，在这里我们介绍正则在PHP中的用法。</p>
                  </blockquote>
                  <h3 id="使用场合"><a href="#使用场合" class="headerlink" title="使用场合"></a>使用场合</h3>
                  <blockquote>
                    <p>1. PHP中，如果可以用字符串处理函数完成的任务，我们就不要使用正则表达式。 2. 有一些复杂的操作，例如格式检验等等，只能用正则表达式完成。 3. 正则表达式也是一个字符串，但是它是具有特殊意义的字符串。 4. 它具有一些编写规则，也是一种模式，也可以把它看做一种编程语言。 5. 只有把正则表达式运用到某个函数中使用，才能发挥出正则表达式的作用，否则，它便是一个简单的字符串。</p>
                  </blockquote>
                  <h3 id="小例子"><a href="#小例子" class="headerlink" title="小例子"></a>小例子</h3>
                  <p>图片的匹配例子</p>
                  <figure class="highlight taggerscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">"/<span class="symbol">\&lt;</span>img<span class="symbol">\s</span>*src=<span class="symbol">\"</span>.*?<span class="symbol">\"</span><span class="symbol">\/</span><span class="symbol">\&gt;</span>/iu"</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>这就是匹配HTML中的一个图片标签，例如可以匹配</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;img <span class="attribute">src</span>=<span class="string">"a.jpg"</span>/&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="PHP中的正则表达式函数库"><a href="#PHP中的正则表达式函数库" class="headerlink" title="PHP中的正则表达式函数库"></a>PHP中的正则表达式函数库</h2>
                  <p>在PHP中，有两套正则表达式函数库。</p>
                  <blockquote>
                    <p>1.POSIX 扩展的正则表达式函数（ereg<em>）。 2.Perl 兼容的正则表达式函数（preg</em>）。</p>
                  </blockquote>
                  <p>Perl 兼容的函数库是后加的函数库，功能更加强大，另外JavaScript 和 Perl 语言里面也会兼容这种模式，所以推荐学习 Perl 语言兼容的函数库。 在学习时，我们就需要学习下面两点</p>
                  <blockquote>
                    <p>1. 正则表达式的语法 2. PHP中正则表达式的处理函数</p>
                  </blockquote>
                  <h2 id="正则表达式的语法"><a href="#正则表达式的语法" class="headerlink" title="正则表达式的语法"></a>正则表达式的语法</h2>
                  <p>任何正则表达式都是由定界符号、原子、元字符、模式修正符号四部分来组成的。下面我们以上面的例子依次来介绍这四部分内容。</p>
                  <figure class="highlight taggerscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">"/<span class="symbol">\&lt;</span>img<span class="symbol">\s</span>*src=<span class="symbol">\"</span>.*?<span class="symbol">\"</span><span class="symbol">\/</span><span class="symbol">\&gt;</span>/iu"</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="1-定界符号"><a href="#1-定界符号" class="headerlink" title="1. 定界符号"></a>1. 定界符号</h3>
                  <p>除了字母，数字和反斜杠 \ 以外的所有字符均可以为定界符。上面的例子中，开头和末尾的两个斜线 / 便作为定界符，我们还可以利用其它字符来定义，例如 | |，{ }，# #等等，不过我们一般是使用斜线 / 作为定界符。</p>
                  <h3 id="2-原子"><a href="#2-原子" class="headerlink" title="2. 原子"></a>2. 原子</h3>
                  <p>上面的例子中，img \s 均为原子。原子是正则表达式的最基本的组成单位，而且必须至少包含一个原子，正则表达式中可以单独使用的字符，就是原子。 使用时注意事项总结如下 <strong>1）原子包括所有打印字符和非打印字符，打印字符就是我们可以在屏幕上看到的字符例如abc等等，非打印字符就是我们看不到的字符，例如空格，回车等等。</strong> <strong>2）\. \* \+ \? \&lt; \( \&lt; \&gt;，所有有意义的字符，如果想作为原子使用，必须统统使用 \ 转义字符转义。</strong> <strong>3）转义字符 \ 可以将有意义的字符转为有意义的字符，例如 <em> 是元字符，代表匹配一个字符零到多次，但是 \</em> 就代表了 * 这个字符。</strong> <strong>4）另外转义字符还可以将没有意义的字符转成有意义的字符，例如 \d 可以表示任意一个十进制数字。总结如下：</strong></p>
                  <blockquote>
                    <p>\d：表示任意一个十进制的数字。 \D：表示任意一个除数字以外的字符。 \s：表示任意一个空白字符，如空格、回车、\t、\n \S：表示任意一个非空白 \w：表示任意一个字，包括 a-z，A-Z，0-9，下划线_ \W：表示任意一个非字，\w 之外的任意一个字符</p>
                  </blockquote>
                  <p><strong>5）自定义原子表，定义一个中括号，表示匹配中括号中的任何一个内容，注意是任何一个。例如</strong></p>
                  <blockquote>
                    <p>正则表达式 “/[123]/“ 和字符串 “abc2”可以匹配成功。 正则表达式 “/[a-z]/“ 和字符串 “x3”可以匹配成功。 正则表达式 “/[1-3a-z]/“ 和字符串 “x”可以匹配成功。</p>
                  </blockquote>
                  <p><strong>在这里<sup><a href="#fn_" id="reffn_"></a></sup>中括号里面写入^代表取反，表示除了原子表中的原子，但是^必须写在[]的第一个字符上。例如</strong></p>
                  <blockquote>
                    <p><sup><a href="#fn_a-z" id="reffn_a-z">a-z</a></sup>代表除了a-z的所有字符 <sup><a href="#fn_\\n\\t" id="reffn_\\n\\t">\\n\\t</a></sup>代表除了换行和制表的所有字符</p>
                  </blockquote>
                  <h3 id="3-元字符"><a href="#3-元字符" class="headerlink" title="3. 元字符"></a>3. 元字符</h3>
                  <p>上面的例子中，<em> ？均为元字符。元字符就是用来修饰原子的字符，不可以单独出现。 例如 </em> 代表匹配前面的原子零到多次，但如果想匹配 <em>，则必须要加转义号 \</em> 来表示 ，特殊地，. 点也可以表示原子 元字符总结分类如下 <strong>1）* 表示其前面的原子可以出现 0 至多次</strong> <strong>2）+ 表示前面的原子可以出现 1 至多次，即至少一个原子</strong> <strong>3）？ 表示前面的原子可以出现 0 次或 1 次</strong> <strong>4）{ } 用于自己定义前面原子出现的次数，另外分为以下几种</strong></p>
                  <blockquote>
                    <p>{m}，m表示一个整数，则前面的数字必须出现m次 {m，n}，m，n表示两个整数，m&lt;n，表示前面出现的原子最少出现 m 次，最多出现 n 次。 {m,} m表示一个整数，表示最少出现 m 次，最多无限 所以 * 可以表示为 {0,}，+ 可以表示为{1,}，? 表示为 {0,1}</p>
                  </blockquote>
                  <p><strong>5）. 默认情况下，表示除换行符外任意一个字符，和 * 组合表示可以匹配任意字符串，和 + 组合表示至少一个字符串</strong> <strong>6）^ 直接在一个正则表达式的第一个字符出现，表示字符串必须以这个正则表达式开始，例如</strong></p>
                  <blockquote>
                    <p>^okay，表示字符串必须以 okay 开头</p>
                  </blockquote>
                  <p><strong>7）$ 直接在一个正则表达式的最后一个字符出现，则表示字符串必须以这个正则表达式结尾，例如</strong></p>
                  <blockquote>
                    <p>okay$，表示字符串必须以 okay 结尾。 注意：^okay$只是匹配一个okay字符，若要匹配 okay 开头okay结尾，则正则表达式可以写为 ^okay.*okay$</p>
                  </blockquote>
                  <p><strong>8）| 表示或的关系，它的优先级是最低的，最后考虑它的功能</strong> <strong>9）\b 表示一个边界，例如</strong></p>
                  <blockquote>
                    <p>字符串 this is island，那么 \bis\b 则可以匹配，它匹配的是中间的 is，is两边是有边界的。</p>
                  </blockquote>
                  <p><strong>10）\B 表示一个非边界，例如</strong></p>
                  <blockquote>
                    <p>\Bis\b，则匹配第一个is，\bis\B则匹配第三个 is</p>
                  </blockquote>
                  <p><strong>11）（） 括号，重点，作用总结如下</strong></p>
                  <blockquote>
                    <p><strong>（1）将括号里面的元素作为一个大原子使用</strong> 即作为一个整体使用，例如 (abc)+，可以匹配abcabc…. <strong>（2）改变优先级</strong> 加上括号可以提高其优先级别。 <strong>（3）作为子模式使用</strong> 正则表达式中添加括号相当于添加了子模式。全部匹配作为一个大模式，放到数组的第一个元素中，每个()是一个子模式按顺序放到数组的其它元素中去。 在下面所说的 preg_match 方法中，结果会被赋值到 $arr 变量中，先匹配外层模式，再匹配内层模式。</p>
                    <figure class="highlight tex">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="formula">$pattern="/(<span class="tag">\<span class="name">d</span><span class="string">&#123;4&#125;</span></span>(<span class="tag">\<span class="name">W</span></span>)<span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span><span class="tag">\<span class="name">W</span></span><span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span>)<span class="tag">\<span class="name">s</span></span>+(<span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span>(<span class="tag">\<span class="name">W</span></span>)<span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span><span class="tag">\<span class="name">W</span></span><span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span>)<span class="tag">\<span class="name">s</span></span>+(?:am|pm)/"; //正则表达式模式</span></span><br><span class="line"><span class="formula">$</span>string="today is 2010/09/15 15:35:28 pm..."; //需要和上面模式字符串进行匹配的变量字符串</span><br><span class="line">if(preg_match(<span class="formula">$pattern, $</span>string, <span class="formula">$arr))&#123;</span></span><br><span class="line"><span class="formula">print_r($</span>arr);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>结果</p>
                    <figure class="highlight angelscript">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">Array</span><br><span class="line">(</span><br><span class="line">    [<span class="number">0</span>] =&gt; <span class="number">2010</span>/<span class="number">09</span>/<span class="number">15</span> <span class="number">15</span>:<span class="number">35</span>:<span class="number">28</span> pm</span><br><span class="line">    [<span class="number">1</span>] =&gt; <span class="number">2010</span>/<span class="number">09</span>/<span class="number">15</span></span><br><span class="line">    [<span class="number">2</span>] =&gt; /</span><br><span class="line">    [<span class="number">3</span>] =&gt; <span class="number">15</span>:<span class="number">35</span>:<span class="number">28</span></span><br><span class="line">    [<span class="number">4</span>] =&gt; :</span><br><span class="line">)</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p><strong>（4）取消子模式</strong> 就将它作为大原子或者改变优先级使用。 只要在模式前面加一个 ?: 就可以取消子模式，例如</p>
                    <figure class="highlight coq">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">(?:am|<span class="type">pm</span>) //即不把（am|<span class="type">pm</span>）作为一个子模式，直接将 am|<span class="type">pm</span> 看做一个整体来使用。</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p><strong>（5）反向引用</strong> 可以在模式中直接将子模式取出来，再作为正则表达式模式的一部分， 如果是在正则表达式像替换函数preg_replace函数中， 可以将子模式取出， 在被替换的字符串中使用 \1 取第一个子模式、 \2取第二个子模式， …. \5 (注意是单引号还是双引号引起来的正则) “\\1” 在双引号引起来的正则，它是可以解释转义字符的，所以 \1 必须要写成 \\1 ‘\1’ 在单引号引起来的正则中，则不会出现这种情况，\1 仍然可以写成 \1 例如</p>
                    <figure class="highlight tex">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="formula">$pattern="/<span class="tag">\<span class="name">d</span><span class="string">&#123;4&#125;</span></span>(<span class="tag">\<span class="name">W</span></span>)<span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span><span class="tag">\<span class="name">\</span></span>1<span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span><span class="tag">\<span class="name">s</span></span>+<span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span>(<span class="tag">\<span class="name">W</span></span>)<span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span><span class="tag">\<span class="name">\</span></span>2<span class="tag">\<span class="name">d</span><span class="string">&#123;2&#125;</span></span><span class="tag">\<span class="name">s</span></span>+(?:am|pm)/"; //正则表达式模式</span></span><br><span class="line"><span class="formula">$</span>string="today is 2010/09/15 15:35:28 pm..."; //需要和上面模式字符串进行匹配的变量字符串</span><br><span class="line">if(preg_match(<span class="formula">$pattern, $</span>string, <span class="formula">$arr))&#123;</span></span><br><span class="line"><span class="formula"> echo "正则表达式 &lt;b&gt;&#123;$</span>pattern&#125; &lt;/b&gt;和字符串 &lt;b&gt;&#123;<span class="formula">$string&#125;&lt;/b&gt; 匹配成功&lt;br&gt;";</span></span><br><span class="line"><span class="formula"> print_r($</span>arr);</span><br><span class="line"> echo '&lt;/pre&gt;';</span><br><span class="line"> &#125;</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>在上面的例子中，因为(\W)已经匹配了第一个斜杠/，它已经作为第一个子模式保存起来了，我们想继续使用这个匹配，我们就可以用 \\1 来表示，如果是单引号引起来的正则，则直接用 \1 来表示就可以了，后面的 \\2 和它是同样的原理。</p>
                  </blockquote>
                  <h3 id="4-模式修正符号"><a href="#4-模式修正符号" class="headerlink" title="4. 模式修正符号"></a>4. 模式修正符号</h3>
                  <p>上面的例子中，最后 / 后面的 i u 即为模式修正符号。</p>
                  <blockquote>
                    <p><strong>1）就是几个字母</strong> <strong>2）可以一次使用一个，每一个都具有一定的意义，也可以连续使用多个符号</strong> <strong>3）放在最后面，是对整个正则表达式调优用的，也可以说是对正则表达式功能的扩展。</strong> 归类如下： <strong>i</strong>：表示在和模式进行匹配时不区分大小写 <strong>m</strong>：将每一行字符视为新的一行，也就是换行符后任何一行都可以当做一个整体字符串，主要的影响就在于 ^ 号和 $ 号。 例如：</p>
                    <figure class="highlight lasso">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">$pattern = <span class="string">'/^abc/m'</span></span><br><span class="line">$string =<span class="string">'cde</span></span><br><span class="line"><span class="string"> abcd</span></span><br><span class="line"><span class="string"> efg'</span></span><br><span class="line"><span class="comment">//可以匹配成功，因为加入m之后，第二行的abcd也当做一行了，也算是以abc开头</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p> <strong>s</strong>：如果没有使用这个模式修正符号，那么 “.” 是不能当做换行符的，加入s，将字符串视为单行，那么 “.” 也就可以表示换行符了。 <strong>x</strong>：模式中的空白忽略不计，注意是模式中的。</p>
                    <figure class="highlight arcade">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="symbol">$patter</span>n = <span class="string">'/a b c/x'</span></span><br><span class="line"><span class="symbol">$stri</span>ng =<span class="string">'abc'</span></span><br><span class="line"><span class="comment">//可以匹配成功，因为加入x之后，a b c直接当做abc来看</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p><strong>e</strong>：正则表达式必须使用在 preg_replace 函数中使用 <strong>A</strong>：必须以正则表达式开头，也就相当于前面加了 ^ <strong>Z</strong>：必须以正则表达式结尾，相当于后面加了 $ <strong>U</strong>：取消贪婪模式，或者 .*? 也可以取消贪婪模式，不过两个同时使用时会导致相反的结果，相当于负负得正的影响，同时出现则会又开启了贪婪模式 。</p>
                  </blockquote>
                  <p>综上所述，正则表达式的组成为 /原子和元字符/模式修正符号，其中 / 为定界符号，不过有一些语言是不需要这个定界符的，例如 Python 等。</p>
                  <h3 id="5-元字符的优先级（了解）"><a href="#5-元字符的优先级（了解）" class="headerlink" title="5.元字符的优先级（了解）"></a>5.元字符的优先级（了解）</h3>
                  <p>1）\ 转义符最高 2）()，(?:)，{ }，括号其次 3）* + ？ {} 4）^ $ \b 5）|</p>
                  <h3 id="6-常用的正则表达式"><a href="#6-常用的正则表达式" class="headerlink" title="6.常用的正则表达式"></a>6.常用的正则表达式</h3>
                  <p><strong>1）校验数字的表达式</strong></p>
                  <blockquote>
                    <p>1 数字：^[0-9]<em>$ 2 n位的数字：^\d{n}$ 3 至少n位的数字：^\d{n,}$ 4 m-n位的数字：^\d{m,n}$ 5 零和非零开头的数字：^(0|[1-9][0-9]</em>)$ 6 非零开头的最多带两位小数的数字：^([1-9][0-9]<em>)+(.[0-9]{1,2})?$ 7 带1-2位小数的正数或负数：^(\-)?\d+(\.\d{1,2})?$ 8 正数、负数、和小数：^(\-|\+)?\d+(\.\d+)?$ 9 有两位小数的正实数：^[0-9]+(.[0-9]{2})?$ 10 有1~3位小数的正实数：^[0-9]+(.[0-9]{1,3})?$ 11 非零的正整数：^[1-9]\d</em>$ 或 ^([1-9][0-9]<em>){1,3}$ 或 ^\+?[1-9][0-9]</em>$ 12 非零的负整数：^\-[1-9][]0-9”<em>$ 或 ^-[1-9]\d</em>$ 13 非负整数：^\d+$ 或 ^[1-9]\d<em>|0$ 14 非正整数：^-[1-9]\d</em>|0$ 或 ^((-\d+)|(0+))$ 15 非负浮点数：^\d+(\.\d+)?$ 或 ^[1-9]\d<em>\.\d</em>|0\.\d<em>[1-9]\d</em>|0?\.0+|0$ 16 非正浮点数：^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 或 ^(-([1-9]\d<em>\.\d</em>|0\.\d<em>[1-9]\d</em>))|0?\.0+|0$ 17 正浮点数：^[1-9]\d<em>\.\d</em>|0\.\d<em>[1-9]\d</em>$ 或 ^(([0-9]+\.[0-9]<em>[1-9][0-9]</em>)|([0-9]<em>[1-9][0-9]</em>\.[0-9]+)|([0-9]<em>[1-9][0-9]</em>))$ 18 负浮点数：^-([1-9]\d<em>\.\d</em>|0\.\d<em>[1-9]\d</em>)$ 或 ^(-(([0-9]+\.[0-9]<em>[1-9][0-9]</em>)|([0-9]<em>[1-9][0-9]</em>\.[0-9]+)|([0-9]<em>[1-9][0-9]</em>)))$ 19 浮点数：^(-?\d+)(\.\d+)?$ 或 ^-?([1-9]\d<em>\.\d</em>|0\.\d<em>[1-9]\d</em>|0?\.0+|0)$</p>
                  </blockquote>
                  <p><strong>2）校验字符的表达式</strong></p>
                  <blockquote>
                    <p>1 汉字：^[\u4e00-\u9fa5]{0,}$ 2 英文和数字：^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$ 3 长度为3-20的所有字符：^.{3,20}$ 4 由26个英文字母组成的字符串：^[A-Za-z]+$ 5 由26个大写英文字母组成的字符串：^[A-Z]+$ 6 由26个小写英文字母组成的字符串：^[a-z]+$ 7 由数字和26个英文字母组成的字符串：^[A-Za-z0-9]+$ 8 由数字、26个英文字母或者下划线组成的字符串：^\w+$ 或 ^\w{3,20}$ 9 中文、英文、数字包括下划线：^[\u4E00-\u9FA5A-Za-z0-9_]+$ 10 中文、英文、数字但不包括下划线等符号：^[\u4E00-\u9FA5A-Za-z0-9]+$ 或 ^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$ 11 可以输入含有^%&amp;’,;=?$\“等字符：<sup><a href="#fn_%&',;=?$\\x22" id="reffn_%&',;=?$\\x22">%&',;=?$\\x22</a></sup>+ 12 禁止输入含有~的字符：<sup><a href="#fn_~\\x22" id="reffn_~\\x22">~\\x22</a></sup>+</p>
                  </blockquote>
                  <p><strong>3）特殊需求表达式</strong></p>
                  <blockquote>
                    <p>1 Email地址：^\w+([-+.]\w+)<em>@\w+([-.]\w+)</em>\.\w+([-.]\w+)<em>$ 2 域名：[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.? 3 InternetURL：[a-zA-z]+://<sup><a href="#fn_\\s" id="reffn_\\s">\\s</a></sup></em> 或 ^<a href="http://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&amp;=]*)?$">http://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&amp;=]*)?$</a> 4 手机号码：^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$ 5 电话号码(“XXX-XXXXXXX”、”XXXX-XXXXXXXX”、”XXX-XXXXXXX”、”XXX-XXXXXXXX”、”XXXXXXX”和”XXXXXXXX)：^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$ 6 国内电话号码(0511-4405222、021-87888822)：\d{3}-\d{8}|\d{4}-\d{7} 7 身份证号(15位、18位数字)：^\d{15}|\d{18}$ 8 短身份证号码(数字、字母x结尾)：^([0-9]){7,18}(x|X)?$ 或 ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$ 9 帐号是否合法(字母开头，允许5-16字节，允许字母数字下划线)：^[a-zA-Z][a-zA-Z0-9_]{4,15}$ 10 密码(以字母开头，长度在6~18之间，只能包含字母、数字和下划线)：^[a-zA-Z]\w{5,17}$ 11 强密码(必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间)：^(?=.<em>\d)(?=.</em>[a-z])(?=.<em>[A-Z]).{8,10}$ 12 日期格式：^\d{4}-\d{1,2}-\d{1,2} 13 一年的12个月(01～09和1～12)：^(0?[1-9]|1[0-2])$ 14 一个月的31天(01～09和1～31)：^((0?[1-9])|((1|2)[0-9])|30|31)$ 15 钱的输入格式： 16 1.有四种钱的表示形式我们可以接受:”10000.00” 和 “10,000.00”, 和没有 “分” 的 “10000” 和 “10,000”：^[1-9][0-9]</em>$ 17 2.这表示任意一个不以0开头的数字,但是,这也意味着一个字符”0”不通过,所以我们采用下面的形式：^(0|[1-9][0-9]<em>)$ 18 3.一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号：^(0|-?[1-9][0-9]</em>)$ 19 4.这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分：^[0-9]+(.[0-9]+)?$ 20 5.必须说明的是,小数点后面至少应该有1位数,所以”10.”是不通过的,但是 “10” 和 “10.2” 是通过的：^[0-9]+(.[0-9]{2})?$ 21 6.这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样：^[0-9]+(.[0-9]{1,2})?$ 22 7.这样就允许用户只写一位小数.下面我们该考虑数字中的逗号了,我们可以这样：^[0-9]{1,3}(,[0-9]{3})<em>(.[0-9]{1,2})?$ 23 8.1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须：^([0-9]+|[0-9]{1,3}(,[0-9]{3})</em>)(.[0-9]{1,2})?$ 24 备注：这就是最终结果了,别忘了”+”可以用”<em>“替代如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里 25 xml文件：^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$ 26 中文字符的正则表达式：[\u4e00-\u9fa5] 27 双字节字符：<sup><a href="#fn_\\x00-\\xff" id="reffn_\\x00-\\xff">\\x00-\\xff</a></sup> (包括汉字在内，可以用来计算字符串的长度(一个双字节字符长度计2，ASCII字符计1)) 28 空白行的正则表达式：\n\s</em>\r (可以用来删除空白行) 29 HTML标记的正则表达式：&lt;(\S<em>?)<sup><a href="#fn_>" id="reffn_>">></a></sup></em>&gt;.<em>?&lt;/\1&gt;|&lt;.</em>? /&gt; (网上流传的版本太糟糕，上面这个也仅仅能部分，对于复杂的嵌套标记依旧无能为力) 30 首尾空白字符的正则表达式：^\s<em>|\s</em>$或(^\s<em>)|(\s</em>$) (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等)，非常有用的表达式) 31 腾讯QQ号：[1-9][0-9]{4,} (腾讯QQ号从10000开始) 32 中国邮政编码：[1-9]\d{5}(?!\d) (中国邮政编码为6位数字) 33 IP地址：\d+\.\d+\.\d+\.\d+ (提取IP地址时有用)</p>
                  </blockquote>
                  <h2 id="PHP正则表达式处理函数"><a href="#PHP正则表达式处理函数" class="headerlink" title="PHP正则表达式处理函数"></a>PHP正则表达式处理函数</h2>
                  <h3 id="1-int-preg-match-string-pattern-string-subject-array-matches-int-flags"><a href="#1-int-preg-match-string-pattern-string-subject-array-matches-int-flags" class="headerlink" title="1. int preg_match ( string pattern, string subject [, array matches [, int flags]] )"></a>1. int preg_match ( string pattern, string subject [, array matches [, int flags]] )</h3>
                  <p>用法：</p>
                  <blockquote>
                    <p>1）在 subject 字符串中搜索与 pattern 给出的正则表达式相匹配的内容。 2）如果提供了 matches，则其会被搜索的结果所填充。$matches[0] 将包含与整个模式匹配的文本，$matches[1] 将包含与第一个捕获的括号中的子模式所匹配的文本，以此类推。 3）flags 参数自 PHP 4.3.0 起可用，flags 可以是下列标记： PREG_OFFSET_CAPTURE 如果设定本标记，对每个出现的匹配结果也同时返回其附属的字符串偏移量。注意这改变了返回的数组的值，使其中的每个单元也是一个数组，其中第一项为匹配字符串，第二项为其偏移量。</p>
                  </blockquote>
                  <p>例如下面的例子，匹配一个URL</p>
                  <figure class="highlight bash">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="variable">$str</span>=<span class="string">"这是一个正则表https://www.baidu.com达式的匹配函数"</span>;</span><br><span class="line"></span><br><span class="line"><span class="variable">$url</span>=<span class="string">"/(https?|ftps?):\/\/((www|mail|news)\.([^\.\/]+)\.(com|org|net))/i"</span>;</span><br><span class="line"><span class="keyword">if</span>(preg_match(<span class="variable">$url</span>, <span class="variable">$str</span>, <span class="variable">$arr</span>))&#123;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"字符串中有正确的URL信息&lt;br&gt;"</span>;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">'&lt;pre&gt;'</span>;</span><br><span class="line">print_r(<span class="variable">$arr</span>);</span><br><span class="line"><span class="built_in">echo</span> <span class="string">'&lt;/pre&gt;'</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"主机："</span>.<span class="variable">$arr</span>[2].<span class="string">"&lt;br&gt;"</span>;</span><br><span class="line"></span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"字符串中不包括URL"</span>;</span><br><span class="line">&#125;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="2-int-preg-match-all-string-pattern-string-subject-array-matches-int-flags"><a href="#2-int-preg-match-all-string-pattern-string-subject-array-matches-int-flags" class="headerlink" title="2. int preg_match_all ( string pattern, string subject [, array matches [, int flags]] )"></a>2. int preg_match_all ( string pattern, string subject [, array matches [, int flags]] )</h3>
                  <p>与 preg_match_all 用法完全一致，不过它匹配的是所有的信息。 例如下面的例子，匹配的是所有符合正则表达式的内容</p>
                  <figure class="highlight stata">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="variable">$str</span>="这是一个正则表https:<span class="comment">//www.baidu.com达式的匹配函数</span></span><br><span class="line">这是一个正则表http:<span class="comment">//www.baidu1.com达式的匹配函数</span></span><br><span class="line">这是一个正则表https:<span class="comment">//mail.baidu2.com达式的匹配函数</span></span><br><span class="line">这是一个正则表https:<span class="comment">//news.baidu3.com达式的匹配函数</span></span><br><span class="line">这是一个正则表https:<span class="comment">//www.baidu4.org达式的匹配函数</span></span><br><span class="line">这是一个正则表https:<span class="comment">//www.baidu5.net达式的匹配函数</span></span><br><span class="line">这是一个正则表ftps:<span class="comment">//www.baidu6.com达式的匹配函数</span></span><br><span class="line">这是一个正则表ftp:<span class="comment">//www.google7.com达式的匹配函数</span></span><br><span class="line">这是一个正则表https:<span class="comment">//www.baidu7.net达式的匹配函数</span></span><br><span class="line">";</span><br><span class="line"><span class="variable">$url</span>=<span class="string">"/(https?|ftps?):\/\/((www|mail|news)\.([^\.\/]+)\.(com|org|net))/i"</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span>(preg_match_all(<span class="variable">$url</span>, <span class="variable">$str</span>, <span class="variable">$arr</span>))&#123;</span><br><span class="line">echo <span class="string">"字符串中有正确的URL信息&lt;br&gt;"</span>;</span><br><span class="line">echo '&lt;pre&gt;';</span><br><span class="line">print_r(<span class="variable">$arr</span>);</span><br><span class="line">echo '&lt;/pre&gt;';</span><br><span class="line"></span><br><span class="line">echo <span class="string">"主机："</span>.<span class="variable">$arr</span>[2].<span class="string">"&lt;br&gt;"</span>;</span><br><span class="line"></span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">echo <span class="string">"字符串中不包括URL"</span>;</span><br><span class="line">&#125;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>上面的输出结果 $arr 的结果没有将一次次匹配的结果分开，也就是所有的子模式都写入一个数组中，没有将结果分成单独的一个数组。 结果中 第零个数组包含了所有的全模式，第一个数组包含了所有的第一个子模式。 可以通过修改上面的代码，实现结果的分开显示。</p>
                  <figure class="highlight bash">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">if</span>(preg_match_all(<span class="variable">$url</span>, <span class="variable">$str</span>, <span class="variable">$arr</span>,PREG_SET_ORDER))&#123;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"字符串中有正确的URL信息&lt;br&gt;"</span>;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">'&lt;pre&gt;'</span>;</span><br><span class="line">print_r(<span class="variable">$arr</span>);</span><br><span class="line"><span class="built_in">echo</span> <span class="string">'&lt;/pre&gt;'</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="string">"主机："</span>.<span class="variable">$arr</span>[2].<span class="string">"&lt;br&gt;"</span>;</span><br><span class="line"></span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line"><span class="built_in">echo</span> <span class="string">"字符串中不包括URL"</span>;</span><br><span class="line">&#125;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>在上面的 preg_match_all 方法中，第四个参数传入 PREG_SET_ORDER，即可实现每一个全模式和子模式的分开展示。 其实，默认模式的参数即为 PREG_PATTERN_ORDER，传入该参数即相当于不传入参数。</p>
                  <h3 id="3-mixed-preg-replace-mixed-pattern-mixed-replacement-mixed-subject-int-limit"><a href="#3-mixed-preg-replace-mixed-pattern-mixed-replacement-mixed-subject-int-limit" class="headerlink" title="3.mixed preg_replace(mixed pattern,mixed replacement,mixed subject [,int limit])"></a>3.mixed preg_replace(mixed pattern,mixed replacement,mixed subject [,int limit])</h3>
                  <p>替换函数，pattern是正则表达式，replacement是替换成的内容，也就是把匹配到符合正则表达式的内容替换为 replacement，subject是查找的字符串，即替换的是这个字符串里面的内容。</p>
                  <figure class="highlight bash">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="variable">$str</span>=<span class="string">" 字符串中php的替换函数，系统提供的 字符串中的替换函数，系统提供的 字符串中的替换函数，系统提供的 字符串中的替换函数，系统提供的 字lamp符串中的替换函数，系统php提供的 字符串中的替换函数"</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$str</span>.<span class="string">"&lt;br&gt;"</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> preg_replace(<span class="string">"/[a-zA-z]+/"</span>,<span class="string">''</span>,<span class="variable">$str</span>);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>执行该程序就会将str字符串中的字母替换为空。 另外，可以指定替换的次数，也就是第四个参数</p>
                  <figure class="highlight bash">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="variable">$str</span>=<span class="string">" 字符串中php的替换函数，系统提供的 字符串中的替换函数，系统提供的 字符串中的替换函数，系统提供的 字符串中的替换函数，系统提供的 字lamp符串中的替换函数，系统php提供的 字符串中的替换函数"</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> <span class="variable">$str</span>.<span class="string">"&lt;br&gt;"</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> preg_replace(<span class="string">"/[a-zA-z]+/"</span>,<span class="string">''</span>,<span class="variable">$str</span>,3);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>这样，就可以实现只替换三次。 另外，可以实现多对多数组的替换，这是一个比较常用的方法，例如</p>
                  <figure class="highlight markdown">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">$str=" 字符串中php的替换函数，系统提供的 字符串中的替换函数，系统提供的 字符串中的替换函数，系统提供的 字符串中的替换函数，系统提供的 字lamp符串中的替换函数，[b]系统php提供的 字符串中[/b]的替换函数，系统提供php的 字符串中的替换函数，系统提供的 字符串中的替换函数，系统提供的 字符<span class="xml"><span class="tag">&lt;<span class="name">b</span>&gt;</span></span>apache<span class="xml"><span class="tag">&lt;/<span class="name">b</span>&gt;</span></span>串中的替换函数，系统提供的 [u]mysql字符串中的替换函[/u]数，系统Apache提供的 字符串中的MySQL替换函数，系php统提供的 [i]字符串中的替换函数[/i]，系统提供的[size=7] 字符串中的php替换[/size]函数，系统提供的[color=Magenta] 字linux符串中的替[/color]换mysql函数，系统提供的php 字符串中的替换函数，系统提供的 字符串中的替换函数，系统php提供的 字符串中的替换函数，系统提供的 字[align=center]符串[b]系统php提供的 字符串中[/b]中的替换函数[/align]，系[b]系统php提供的 字符串中[/b]统提php供的 字符串中的替换函数，系统提供的";</span><br><span class="line"></span><br><span class="line">echo $str."<span class="xml"><span class="tag">&lt;<span class="name">br</span>&gt;</span></span>";</span><br><span class="line"></span><br><span class="line">$ubbcodes=array(</span><br><span class="line">'/[<span class="string">b</span>](<span class="link">.*?</span>)[<span class="string">\/b</span>]/i',</span><br><span class="line">'/[<span class="string">u</span>](<span class="link">.*?</span>)[<span class="string">\/u</span>]/i',</span><br><span class="line">'/[<span class="string">i</span>](<span class="link">.*?</span>)[<span class="string">\/i</span>]/i',</span><br><span class="line">'/[<span class="string">color=(.*?)</span>](<span class="link">.*?</span>)[<span class="string">\/color</span>]/',</span><br><span class="line">'/[<span class="string">size=(.*?)</span>](<span class="link">.*?</span>)[<span class="string">\/size</span>]/',</span><br><span class="line">'/[<span class="string">align=(.*?)</span>](<span class="link">.*?</span>)[<span class="string">\/align</span>]/'</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">$htmls=array(</span><br><span class="line">'<span class="xml"><span class="tag">&lt;<span class="name">b</span>&gt;</span></span>\1<span class="xml"><span class="tag">&lt;/<span class="name">b</span>&gt;</span></span>',</span><br><span class="line">'<span class="xml"><span class="tag">&lt;<span class="name">u</span>&gt;</span></span>\1<span class="xml"><span class="tag">&lt;/<span class="name">u</span>&gt;</span></span>',</span><br><span class="line">'<span class="xml"><span class="tag">&lt;<span class="name">i</span>&gt;</span></span>\1<span class="xml"><span class="tag">&lt;/<span class="name">i</span>&gt;</span></span>',</span><br><span class="line">'<span class="xml"><span class="tag">&lt;<span class="name">font</span> <span class="attr">color</span>=<span class="string">"\1"</span>&gt;</span></span>\2<span class="xml"><span class="tag">&lt;/<span class="name">font</span>&gt;</span></span>',</span><br><span class="line">'<span class="xml"><span class="tag">&lt;<span class="name">font</span> <span class="attr">size</span>=<span class="string">"\1"</span>&gt;</span></span>\2<span class="xml"><span class="tag">&lt;/<span class="name">font</span>&gt;</span></span>',</span><br><span class="line">'<span class="xml"><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"\1"</span>&gt;</span></span>\2<span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span>'</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">echo preg_replace($ubbcodes,$htmls,$str);</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>上面就可以实现中括号标签转化为HTML标签。 好，关于正则表达式函数，掌握这三个就基本够用了，其他的还有正则表达式分割函数，直接用PHP里面的字符串分割即可，不在此叙述了。</p>
                  <h2 id="本篇总结"><a href="#本篇总结" class="headerlink" title="本篇总结"></a>本篇总结</h2>
                  <p><strong>本篇介绍了正则表达式的相关语法以及在PHP中的正则表达式匹配函数，以上所有便是PHP正则表达式的相关内容，希望对大家有帮助~</strong></p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-28 19:00:28" itemprop="dateCreated datePublished" datetime="2015-02-28T19:00:28+08:00">2015-02-28</time>
                </span>
                <span id="/1186.html" class="post-meta-item leancloud_visitors" data-flag-title="PHP高级特性一之正则表达式用法" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>11k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>10 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1076.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/1076.html" class="post-title-link" itemprop="url">Python爬虫实战五之模拟登录淘宝并获取所有订单</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>经过多次尝试，模拟登录淘宝终于成功了，实在是不容易，淘宝的登录加密和验证太复杂了，煞费苦心，在此写出来和大家一起分享，希望大家支持。</p>
                  <h2 id="温馨提示"><a href="#温馨提示" class="headerlink" title="温馨提示"></a>温馨提示</h2>
                  <p>更新时间，2016-02-01，现在淘宝换成了滑块验证了，比较难解决这个问题，以下的代码没法用了，仅作学习参考研究之用吧。</p>
                  <h2 id="本篇内容"><a href="#本篇内容" class="headerlink" title="本篇内容"></a>本篇内容</h2>
                  <p>1. python模拟登录淘宝网页 2. 获取登录用户的所有订单详情 3. 学会应对出现验证码的情况 4. 体会一下复杂的模拟登录机制</p>
                  <h2 id="探索部分成果"><a href="#探索部分成果" class="headerlink" title="探索部分成果"></a>探索部分成果</h2>
                  <p>1. 淘宝的密码用了AES加密算法，最终将密码转化为256位，在POST时，传输的是256位长度的密码。 2. 淘宝在登录时必须要输入验证码，在经过几次尝试失败后最终获取了验证码图片让用户手动输入来验证。 3. 淘宝另外有复杂且每天在变的 ua 加密算法，在程序中我们需要提前获取某一 ua 码才可进行模拟登录。 4. 在获取最后的登录 st 码时，历经了多次请求和正则表达式提取，且 st 码只可使用一次。</p>
                  <h2 id="整体思路梳理"><a href="#整体思路梳理" class="headerlink" title="整体思路梳理"></a>整体思路梳理</h2>
                  <p>1. 手动到浏览器获取 ua 码以及 加密后的密码，只获取一次即可，一劳永逸。 2. 向登录界面发送登录请求，POST 一系列参数，包括 ua 码以及密码等等，获得响应，提取验证码图像。 3. 用户输入手动验证码，重新加入验证码数据再次用 POST 方式发出请求，获得响应，提取 J_Htoken。 4. 利用 J_Htoken 向 alipay 发出请求，获得响应，提取 st 码。 5. 利用 st 码和用户名，重新发出登录请求，获得响应，提取重定向网址，存储 cookie。 6. 利用 cookie 向其他个人页面如订单页面发出请求，获得响应，提取订单详情。 是不是没看懂？没事，下面我将一点点说明自己模拟登录的过程，希望大家可以理解。</p>
                  <h2 id="前期准备"><a href="#前期准备" class="headerlink" title="前期准备"></a>前期准备</h2>
                  <p>由于淘宝的 ua 算法和 aes 密码加密算法太复杂了，ua 算法在淘宝每天都是在变化的，不过，这个内容你获取之后一直用即可，经过测试之后没有问题，一劳永逸。 那么 ua 和 aes 密码怎样获取呢？ 我们就从浏览器里面直接获取吧，打开浏览器，找到淘宝的登录界面，按 F12 或者浏览器右键审查元素。 在这里我用的是火狐浏览器，首先记得在浏览器中设置一下显示持续日志，要不然页面跳转了你就看不到之前抓取的信息了。在这里截图如下： <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150225013600.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150225013600.jpg" alt="20150225013600"></a> 好，那么接下来我们就从浏览器中获取 ua 和 aes 密码 点击网络选项卡，这时都是空的，什么数据也没有截取。这时你就在网页上登录一下试试吧，输入用户名啊，密码啊，有必要时需要输入验证码，点击登录。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225014124.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225014124.jpg" alt="QQ截图20150225014124"></a> 等跳转成功后，你就可以看到好多日志记录了，点击图中的那一行 login.taobo.com，然后查看参数，你就会发现表单数据了，其中就包括 ua 还有下面的 password2，把这俩复制下来，我们之后要用到的。这就是我们需要的 ua 还有 aes 加密后的密码。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225014019.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225014019.jpg" alt="QQ截图20150225014019"></a> 恩，读到这里，你应该获取到了属于自己的 ua 和 password2 两个内容。</p>
                  <h2 id="输入验证码并获取J-HToken"><a href="#输入验证码并获取J-HToken" class="headerlink" title="输入验证码并获取J_HToken"></a>输入验证码并获取J_HToken</h2>
                  <p>经过博主本人亲自验证，有时候，在模拟登录时你并不需要输入验证码，它直接返回的结果就是前面所说的下一步用到的 J_Token，而有时候你则会需要输入验证码，等你手动输入验证码之后，重新请求登录一次。 博主是边写程序边更新文章的，现在写完了是否有必要输入验证码的检验以及在浏览器中呈现验证码。 代码如下</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> urllib</span><br><span class="line"><span class="keyword">import</span> urllib2</span><br><span class="line"><span class="keyword">import</span> cookielib</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">import</span> webbrowser</span><br><span class="line"></span><br><span class="line"><span class="comment">#模拟登录淘宝类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Taobao</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#初始化方法</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#登录的URL</span></span><br><span class="line">        self.loginURL = <span class="string">"https://login.taobao.com/member/login.jhtml"</span></span><br><span class="line">        <span class="comment">#代理IP地址，防止自己的IP被封禁</span></span><br><span class="line">        self.proxyURL = <span class="string">'http://120.193.146.97:843'</span></span><br><span class="line">        <span class="comment">#登录POST数据时发送的头部信息</span></span><br><span class="line">        self.loginHeaders =  &#123;</span><br><span class="line">            <span class="string">'Host'</span>:<span class="string">'login.taobao.com'</span>,</span><br><span class="line">            <span class="string">'User-Agent'</span> : <span class="string">'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0'</span>,</span><br><span class="line">            <span class="string">'Referer'</span> : <span class="string">'https://login.taobao.com/member/login.jhtml'</span>,</span><br><span class="line">            <span class="string">'Content-Type'</span>: <span class="string">'application/x-www-form-urlencoded'</span>,</span><br><span class="line">            <span class="string">'Connection'</span> : <span class="string">'Keep-Alive'</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">#用户名</span></span><br><span class="line">        self.username = <span class="string">'cqcre'</span></span><br><span class="line">        <span class="comment">#ua字符串，经过淘宝ua算法计算得出，包含了时间戳,浏览器,屏幕分辨率,随机数,鼠标移动,鼠标点击,其实还有键盘输入记录,鼠标移动的记录、点击的记录等等的信息</span></span><br><span class="line">        self.ua = <span class="string">'191UW5TcyMNYQwiAiwTR3tCf0J/QnhEcUpkMmQ=|Um5Ockt0TXdPc011TXVKdyE=|U2xMHDJ+H2QJZwBxX39Rb1d5WXcrSixAJ1kjDVsN|VGhXd1llXGNaYFhkWmJaYl1gV2pIdUtyTXRKfkN4Qn1FeEF6R31TBQ==|VWldfS0TMw8xDjYWKhAwHiUdOA9wCDEVaxgkATdcNU8iDFoM|VmNDbUMV|V2NDbUMV|WGRYeCgGZhtmH2VScVI2UT5fORtmD2gCawwuRSJHZAFsCWMOdVYyVTpbPR99HWAFYVMpUDUFORshHiQdJR0jAT0JPQc/BDoFPgooFDZtVBR5Fn9VOwt2EWhCOVQ4WSJPJFkHXhgoSDVIMRgnHyFqQ3xEezceIRkmahRqFDZLIkUvRiEDaA9qQ3xEezcZORc5bzk=|WWdHFy0TMw8vEy0UIQE0ADgYJBohGjoAOw4uEiwXLAw2DThu9a==|WmBAED5+KnIbdRh1GXgFQSZbGFdrUm1UblZqVGxQa1ZiTGxQcEp1I3U=|W2NDEz19KXENZwJjHkY7Ui9OJQsre09zSWlXY1oMLBExHzERLxsuE0UT|XGZGFjh4LHQdcx5zH34DRyBdHlFtVGtSaFBsUmpWbVBkSmpXd05zTnMlcw==|XWdHFzl5LXUJYwZnGkI/VitKIQ8vEzMKNws3YTc=|XmdaZ0d6WmVFeUB8XGJaYEB4TGxWbk5yTndXa0tyT29Ta0t1QGBeZDI='</span></span><br><span class="line">        <span class="comment">#密码，在这里不能输入真实密码，淘宝对此密码进行了加密处理，256位，此处为加密后的密码</span></span><br><span class="line">        self.password2 = <span class="string">'7511aa68sx629e45de220d29174f1066537a73420ef6dbb5b46f202396703a2d56b0312df8769d886e6ca63d587fdbb99ee73927e8c07d9c88cd02182e1a21edc13fb8e140a4a2a4b5c253bf38484bd0e08199e03eb9bf7b365a5c673c03407d812b91394f0d3c7564042e3f2b11d156aeea37ad6460118914125ab8f8ac466f'</span></span><br><span class="line">        self.post = post = &#123;</span><br><span class="line">            <span class="string">'ua'</span>:self.ua,</span><br><span class="line">            <span class="string">'TPL_checkcode'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'CtrlVersion'</span>: <span class="string">'1,0,0,7'</span>,</span><br><span class="line">            <span class="string">'TPL_password'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'TPL_redirect_url'</span>:<span class="string">'http://i.taobao.com/my_taobao.htm?nekot=udm8087E1424147022443'</span>,</span><br><span class="line">            <span class="string">'TPL_username'</span>:self.username,</span><br><span class="line">            <span class="string">'loginsite'</span>:<span class="string">'0'</span>,</span><br><span class="line">            <span class="string">'newlogin'</span>:<span class="string">'0'</span>,</span><br><span class="line">            <span class="string">'from'</span>:<span class="string">'tb'</span>,</span><br><span class="line">            <span class="string">'fc'</span>:<span class="string">'default'</span>,</span><br><span class="line">            <span class="string">'style'</span>:<span class="string">'default'</span>,</span><br><span class="line">            <span class="string">'css_style'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'tid'</span>:<span class="string">'XOR_1_000000000000000000000000000000_625C4720470A0A050976770A'</span>,</span><br><span class="line">            <span class="string">'support'</span>:<span class="string">'000001'</span>,</span><br><span class="line">            <span class="string">'loginType'</span>:<span class="string">'4'</span>,</span><br><span class="line">            <span class="string">'minititle'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'minipara'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'umto'</span>:<span class="string">'NaN'</span>,</span><br><span class="line">            <span class="string">'pstrong'</span>:<span class="string">'3'</span>,</span><br><span class="line">            <span class="string">'llnick'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'sign'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'need_sign'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'isIgnore'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'full_redirect'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'popid'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'callback'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'guf'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'not_duplite_str'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'need_user_id'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'poy'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'gvfdcname'</span>:<span class="string">'10'</span>,</span><br><span class="line">            <span class="string">'gvfdcre'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'from_encoding '</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'sub'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'TPL_password_2'</span>:self.password2,</span><br><span class="line">            <span class="string">'loginASR'</span>:<span class="string">'1'</span>,</span><br><span class="line">            <span class="string">'loginASRSuc'</span>:<span class="string">'1'</span>,</span><br><span class="line">            <span class="string">'allp'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'oslanguage'</span>:<span class="string">'zh-CN'</span>,</span><br><span class="line">            <span class="string">'sr'</span>:<span class="string">'1366*768'</span>,</span><br><span class="line">            <span class="string">'osVer'</span>:<span class="string">'windows|6.1'</span>,</span><br><span class="line">            <span class="string">'naviVer'</span>:<span class="string">'firefox|35'</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">#将POST的数据进行编码转换</span></span><br><span class="line">        self.postData = urllib.urlencode(self.post)</span><br><span class="line">        <span class="comment">#设置代理</span></span><br><span class="line">        self.proxy = urllib2.ProxyHandler(&#123;<span class="string">'http'</span>:self.proxyURL&#125;)</span><br><span class="line">        <span class="comment">#设置cookie</span></span><br><span class="line">        self.cookie = cookielib.LWPCookieJar()</span><br><span class="line">        <span class="comment">#设置cookie处理器</span></span><br><span class="line">        self.cookieHandler = urllib2.HTTPCookieProcessor(self.cookie)</span><br><span class="line">        <span class="comment">#设置登录时用到的opener，它的open方法相当于urllib2.urlopen</span></span><br><span class="line">        self.opener = urllib2.build_opener(self.cookieHandler,self.proxy,urllib2.HTTPHandler)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#得到是否需要输入验证码，这次请求的相应有时会不同，有时需要验证有时不需要</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">needIdenCode</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#第一次登录获取验证码尝试，构建request</span></span><br><span class="line">        request = urllib2.Request(self.loginURL,self.postData,self.loginHeaders)</span><br><span class="line">        <span class="comment">#得到第一次登录尝试的相应</span></span><br><span class="line">        response = self.opener.open(request)</span><br><span class="line">        <span class="comment">#获取其中的内容</span></span><br><span class="line">        content = response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">        <span class="comment">#获取状态吗</span></span><br><span class="line">        status = response.getcode()</span><br><span class="line">        <span class="comment">#状态码为200，获取成功</span></span><br><span class="line">        <span class="keyword">if</span> status == <span class="number">200</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"获取请求成功"</span></span><br><span class="line">            <span class="comment">#\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801这六个字是请输入验证码的utf-8编码</span></span><br><span class="line">            pattern = re.compile(<span class="string">u'\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801'</span>,re.S)</span><br><span class="line">            result = re.search(pattern,content)</span><br><span class="line">            <span class="comment">#如果找到该字符，代表需要输入验证码</span></span><br><span class="line">            <span class="keyword">if</span> result:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"此次安全验证异常，您需要输入验证码"</span></span><br><span class="line">                <span class="keyword">return</span> content</span><br><span class="line">            <span class="comment">#否则不需要</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"此次安全验证通过，您这次不需要输入验证码"</span></span><br><span class="line">                <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"获取请求失败"</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#得到验证码图片</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getIdenCode</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        <span class="comment">#得到验证码的图片</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;img id="J_StandardCode_m.*?data-src="(.*?)"'</span>,re.S)</span><br><span class="line">        <span class="comment">#匹配的结果</span></span><br><span class="line">        matchResult = re.search(pattern,page)</span><br><span class="line">        <span class="comment">#已经匹配得到内容，并且验证码图片链接不为空</span></span><br><span class="line">        <span class="keyword">if</span> matchResult <span class="keyword">and</span> matchResult.group(<span class="number">1</span>):</span><br><span class="line">            <span class="keyword">print</span> matchResult.group(<span class="number">1</span>)</span><br><span class="line">            <span class="keyword">return</span> matchResult.group(<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"没有找到验证码内容"</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#程序运行主干</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#是否需要验证码，是则得到页面内容，不是则返回False</span></span><br><span class="line">        needResult = self.needIdenCode()</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> needResult == <span class="literal">False</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"您需要手动输入验证码"</span></span><br><span class="line">            idenCode = self.getIdenCode(needResult)</span><br><span class="line">            <span class="comment">#得到了验证码的链接</span></span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> idenCode == <span class="literal">False</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"验证码获取成功"</span></span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"请在浏览器中输入您看到的验证码"</span></span><br><span class="line">                webbrowser.open_new_tab(idenCode)</span><br><span class="line">            <span class="comment">#验证码链接为空，无效验证码</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"验证码获取失败，请重试"</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"不需要输入验证码"</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">taobao = Taobao()</span><br><span class="line">taobao.main()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>恩，请把里面的 ua 和 password2 还有用户名换成自己的进行尝试，用我的可能会产生错误的。 运行结果 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225015508.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225015508.jpg" alt="QQ截图20150225015508"></a> 然后会蹦出浏览器，显示了验证码的内容，这个需要你来手动输入。 在这里有小伙伴向我反映有这么个错误 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ图片20150227181617.png" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ图片20150227181617.png" alt="QQ图片20150227181617"></a> 经过查证，竟然是版本问题，博主本人用的是 2.7.7，而小伙伴用的是 2.7.9。后来换成 2.7.7 就好了…，我也是醉了，希望有相同错误的小伙伴，可以尝试换一下版本… 好啦，运行时会弹出浏览器，如图 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225015717.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225015717.jpg" alt="QQ截图20150225015717"></a> 那么，我们现在需要手动输入验证码，重新向登录界面发出登录请求，之前的post数据内容加入验证码这一项，重新请求一次，如果请求成功，则会返回下一步我们需要的 J_HToken，如果验证码输入错误，则会返回验证码输入错误的选项。好，下面，我已经写到了获取J_HToken的进度，代码如下，现在运行程序，会蹦出浏览器，然后提示你输入验证码，用户手动输入之后，则会返回一个页面，我们提取出 J_Htoken即可。 注意，到现在为止，你还没有登录成功，只是获取到了J_HToken的值。 目前写到的代码如下</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> urllib</span><br><span class="line"><span class="keyword">import</span> urllib2</span><br><span class="line"><span class="keyword">import</span> cookielib</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">import</span> webbrowser</span><br><span class="line"></span><br><span class="line"><span class="comment">#模拟登录淘宝类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Taobao</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#初始化方法</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#登录的URL</span></span><br><span class="line">        self.loginURL = <span class="string">"https://login.taobao.com/member/login.jhtml"</span></span><br><span class="line">        <span class="comment">#代理IP地址，防止自己的IP被封禁</span></span><br><span class="line">        self.proxyURL = <span class="string">'http://120.193.146.97:843'</span></span><br><span class="line">        <span class="comment">#登录POST数据时发送的头部信息</span></span><br><span class="line">        self.loginHeaders =  &#123;</span><br><span class="line">            <span class="string">'Host'</span>:<span class="string">'login.taobao.com'</span>,</span><br><span class="line">            <span class="string">'User-Agent'</span> : <span class="string">'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0'</span>,</span><br><span class="line">            <span class="string">'Referer'</span> : <span class="string">'https://login.taobao.com/member/login.jhtml'</span>,</span><br><span class="line">            <span class="string">'Content-Type'</span>: <span class="string">'application/x-www-form-urlencoded'</span>,</span><br><span class="line">            <span class="string">'Connection'</span> : <span class="string">'Keep-Alive'</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">#用户名</span></span><br><span class="line">        self.username = <span class="string">'cqcre'</span></span><br><span class="line">        <span class="comment">#ua字符串，经过淘宝ua算法计算得出，包含了时间戳,浏览器,屏幕分辨率,随机数,鼠标移动,鼠标点击,其实还有键盘输入记录,鼠标移动的记录、点击的记录等等的信息</span></span><br><span class="line">        self.ua = <span class="string">'191UW5TcyMNYQwiAiwTR3tCf0J/QnhEcUpkMmQ=|Um5Ockt0TXdPc011TXVKdyE=|U2xMHDJ+H2QJZwBxX39Rb1d5WXcrSixAJ1kjDVsN|VGhXd1llXGNaYFhkWmJaYl1gV2pIdUtyTXRKfkN4Qn1FeEF6R31TBQ==|VWldfS0TMw8xDjYWKhAwHiUdOA9wCDEVaxgkATdcNU8iDFoM|VmNDbUMV|V2NDbUMV|WGRYeCgGZhtmH2VScVI2UT5fORtmD2gCawwuRSJHZAFsCWMOdVYyVTpbPR99HWAFYVMpUDUFORshHiQdJR0jAT0JPQc/BDoFPgooFDZtVBR5Fn9VOwt2EWhCOVQ4WSJPJFkHXhgoSDVIMRgnHyFqQ3xEezceIRkmahRqFDZLIkUvRiEDaA9qQ3xEezcZORc5bzk=|WWdHFy0TMw8vEy0UIQE0ADgYJBohGjoAOw4uEiwXLAw2DThuOA==|WmBAED5+KnIbdRh1GXgFQSZbGFdrUm1UblZqVGxQa1ZiTGxQcEp1I3U=|W2NDEz19KXENZwJjHkY7Ui9OJQsre09zSWlXY1oMLBExHzERLxsuE0UT|XGZGFjh4LHQdcx5zH34DRyBdHlFtVGtSaFBsUmpWbVBkSmpXd05zTnMlcw==|XWdHFzl5LXUJYwZnGkI/VitKIQ8vEzMKNws3YTc=|XmdaZ0d6WmVFeUB8XGJaYEB4TGxWbk5yTndXa0tyT29Ta0t1QGBeZDI='</span></span><br><span class="line">        <span class="comment">#密码，在这里不能输入真实密码，淘宝对此密码进行了加密处理，256位，此处为加密后的密码</span></span><br><span class="line">        self.password2 = <span class="string">'7511aa6854629e45de220d29174f1066537a73420ef6dbb5b46f202396703a2d56b0312df8769d886e6ca63d587fdbb99ee73927e8c07d9c88cd02182e1a21edc13fb8e0a4a2a4b5c253bf38484bd0e08199e03eb9bf7b365a5c673c03407d812b91394f0d3c7564042e3f2b11d156aeea37ad6460118914125ab8f8ac466f'</span></span><br><span class="line">        self.post = post = &#123;</span><br><span class="line">            <span class="string">'ua'</span>:self.ua,</span><br><span class="line">            <span class="string">'TPL_checkcode'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'CtrlVersion'</span>: <span class="string">'1,0,0,7'</span>,</span><br><span class="line">            <span class="string">'TPL_password'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'TPL_redirect_url'</span>:<span class="string">'http://i.taobao.com/my_taobao.htm?nekot=udm8087E1424147022443'</span>,</span><br><span class="line">            <span class="string">'TPL_username'</span>:self.username,</span><br><span class="line">            <span class="string">'loginsite'</span>:<span class="string">'0'</span>,</span><br><span class="line">            <span class="string">'newlogin'</span>:<span class="string">'0'</span>,</span><br><span class="line">            <span class="string">'from'</span>:<span class="string">'tb'</span>,</span><br><span class="line">            <span class="string">'fc'</span>:<span class="string">'default'</span>,</span><br><span class="line">            <span class="string">'style'</span>:<span class="string">'default'</span>,</span><br><span class="line">            <span class="string">'css_style'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'tid'</span>:<span class="string">'XOR_1_000000000000000000000000000000_625C4720470A0A050976770A'</span>,</span><br><span class="line">            <span class="string">'support'</span>:<span class="string">'000001'</span>,</span><br><span class="line">            <span class="string">'loginType'</span>:<span class="string">'4'</span>,</span><br><span class="line">            <span class="string">'minititle'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'minipara'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'umto'</span>:<span class="string">'NaN'</span>,</span><br><span class="line">            <span class="string">'pstrong'</span>:<span class="string">'3'</span>,</span><br><span class="line">            <span class="string">'llnick'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'sign'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'need_sign'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'isIgnore'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'full_redirect'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'popid'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'callback'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'guf'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'not_duplite_str'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'need_user_id'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'poy'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'gvfdcname'</span>:<span class="string">'10'</span>,</span><br><span class="line">            <span class="string">'gvfdcre'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'from_encoding '</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'sub'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'TPL_password_2'</span>:self.password2,</span><br><span class="line">            <span class="string">'loginASR'</span>:<span class="string">'1'</span>,</span><br><span class="line">            <span class="string">'loginASRSuc'</span>:<span class="string">'1'</span>,</span><br><span class="line">            <span class="string">'allp'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'oslanguage'</span>:<span class="string">'zh-CN'</span>,</span><br><span class="line">            <span class="string">'sr'</span>:<span class="string">'1366*768'</span>,</span><br><span class="line">            <span class="string">'osVer'</span>:<span class="string">'windows|6.1'</span>,</span><br><span class="line">            <span class="string">'naviVer'</span>:<span class="string">'firefox|35'</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">#将POST的数据进行编码转换</span></span><br><span class="line">        self.postData = urllib.urlencode(self.post)</span><br><span class="line">        <span class="comment">#设置代理</span></span><br><span class="line">        self.proxy = urllib2.ProxyHandler(&#123;<span class="string">'http'</span>:self.proxyURL&#125;)</span><br><span class="line">        <span class="comment">#设置cookie</span></span><br><span class="line">        self.cookie = cookielib.LWPCookieJar()</span><br><span class="line">        <span class="comment">#设置cookie处理器</span></span><br><span class="line">        self.cookieHandler = urllib2.HTTPCookieProcessor(self.cookie)</span><br><span class="line">        <span class="comment">#设置登录时用到的opener，它的open方法相当于urllib2.urlopen</span></span><br><span class="line">        self.opener = urllib2.build_opener(self.cookieHandler,self.proxy,urllib2.HTTPHandler)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#得到是否需要输入验证码，这次请求的相应有时会不同，有时需要验证有时不需要</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">needCheckCode</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#第一次登录获取验证码尝试，构建request</span></span><br><span class="line">        request = urllib2.Request(self.loginURL,self.postData,self.loginHeaders)</span><br><span class="line">        <span class="comment">#得到第一次登录尝试的相应</span></span><br><span class="line">        response = self.opener.open(request)</span><br><span class="line">        <span class="comment">#获取其中的内容</span></span><br><span class="line">        content = response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">        <span class="comment">#获取状态吗</span></span><br><span class="line">        status = response.getcode()</span><br><span class="line">        <span class="comment">#状态码为200，获取成功</span></span><br><span class="line">        <span class="keyword">if</span> status == <span class="number">200</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"获取请求成功"</span></span><br><span class="line">            <span class="comment">#\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801这六个字是请输入验证码的utf-8编码</span></span><br><span class="line">            pattern = re.compile(<span class="string">u'\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801'</span>,re.S)</span><br><span class="line">            result = re.search(pattern,content)</span><br><span class="line">            <span class="keyword">print</span> content</span><br><span class="line">            <span class="comment">#如果找到该字符，代表需要输入验证码</span></span><br><span class="line">            <span class="keyword">if</span> result:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"此次安全验证异常，您需要输入验证码"</span></span><br><span class="line">                <span class="keyword">return</span> content</span><br><span class="line">            <span class="comment">#否则不需要</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment">#返回结果直接带有J_HToken字样，表明直接验证通过</span></span><br><span class="line">                tokenPattern = re.compile(<span class="string">'id="J_HToken"'</span>)</span><br><span class="line">                tokenMatch = re.search(tokenPattern,content)</span><br><span class="line">                <span class="keyword">if</span> tokenMatch:</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"此次安全验证通过，您这次不需要输入验证码"</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"获取请求失败"</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#得到验证码图片</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getCheckCode</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        <span class="comment">#得到验证码的图片</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;img id="J_StandardCode_m.*?data-src="(.*?)"'</span>,re.S)</span><br><span class="line">        <span class="comment">#匹配的结果</span></span><br><span class="line">        matchResult = re.search(pattern,page)</span><br><span class="line">        <span class="comment">#已经匹配得到内容，并且验证码图片链接不为空</span></span><br><span class="line">        <span class="keyword">if</span> matchResult <span class="keyword">and</span> matchResult.group(<span class="number">1</span>):</span><br><span class="line">            <span class="keyword">print</span> matchResult.group(<span class="number">1</span>)</span><br><span class="line">            <span class="keyword">return</span> matchResult.group(<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"没有找到验证码内容"</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#输入验证码，重新请求，如果验证成功，则返回J_HToken</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">loginWithCheckCode</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#提示用户输入验证码</span></span><br><span class="line">        checkcode = raw_input(<span class="string">'请输入验证码:'</span>)</span><br><span class="line">        <span class="comment">#将验证码重新添加到post的数据中</span></span><br><span class="line">        self.post[<span class="string">'TPL_checkcode'</span>] = checkcode</span><br><span class="line">        <span class="comment">#对post数据重新进行编码</span></span><br><span class="line">        self.postData = urllib.urlencode(self.post)</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="comment">#再次构建请求，加入验证码之后的第二次登录尝试</span></span><br><span class="line">            request = urllib2.Request(self.loginURL,self.postData,self.loginHeaders)</span><br><span class="line">            <span class="comment">#得到第一次登录尝试的相应</span></span><br><span class="line">            response = self.opener.open(request)</span><br><span class="line">            <span class="comment">#获取其中的内容</span></span><br><span class="line">            content = response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">            <span class="comment">#检测验证码错误的正则表达式，\u9a8c\u8bc1\u7801\u9519\u8bef 是验证码错误五个字的编码</span></span><br><span class="line">            pattern = re.compile(<span class="string">u'\u9a8c\u8bc1\u7801\u9519\u8bef'</span>,re.S)</span><br><span class="line">            result = re.search(pattern,content)</span><br><span class="line">            <span class="comment">#如果返回页面包括了，验证码错误五个字</span></span><br><span class="line">            <span class="keyword">if</span> result:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"验证码输入错误"</span></span><br><span class="line">                <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment">#返回结果直接带有J_HToken字样，说明验证码输入成功，成功跳转到了获取HToken的界面</span></span><br><span class="line">                tokenPattern = re.compile(<span class="string">'id="J_HToken" value="(.*?)"'</span>)</span><br><span class="line">                tokenMatch = re.search(tokenPattern,content)</span><br><span class="line">                <span class="comment">#如果匹配成功，找到了J_HToken</span></span><br><span class="line">                <span class="keyword">if</span> tokenMatch:</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"验证码输入正确"</span></span><br><span class="line">                    <span class="keyword">print</span> tokenMatch.group(<span class="number">1</span>)</span><br><span class="line">                    <span class="keyword">return</span> tokenMatch.group(<span class="number">1</span>)</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    <span class="comment">#匹配失败，J_Token获取失败</span></span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"J_Token获取失败"</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        <span class="keyword">except</span> urllib2.HTTPError, e:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"连接服务器出错，错误原因"</span>,e.reason</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#程序运行主干</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#是否需要验证码，是则得到页面内容，不是则返回False</span></span><br><span class="line">        needResult = self.needCheckCode()</span><br><span class="line">        <span class="comment">#请求获取失败，得到的结果是None</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> needResult ==<span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> needResult == <span class="literal">False</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"您需要手动输入验证码"</span></span><br><span class="line">                idenCode = self.getCheckCode(needResult)</span><br><span class="line">                <span class="comment">#得到了验证码的链接</span></span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">not</span> idenCode == <span class="literal">False</span>:</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"验证码获取成功"</span></span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"请在浏览器中输入您看到的验证码"</span></span><br><span class="line">                    webbrowser.open_new_tab(idenCode)</span><br><span class="line">                    J_HToken = self.loginWithCheckCode()</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">"J_HToken"</span>,J_HToken</span><br><span class="line">                <span class="comment">#验证码链接为空，无效验证码</span></span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"验证码获取失败，请重试"</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"不需要输入验证码"</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"请求登录页面失败，无法确认是否需要验证码"</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">taobao = Taobao()</span><br><span class="line">taobao.main()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>现在的运行结果是这样的，我们已经可以得到 J_HToken 了，离成功又迈进了一步。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225200329.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225200329.jpg" alt="QQ截图20150225200329"></a> 好，到现在为止，我们应该可以获取到J_HToken的值啦。</p>
                  <h2 id="利用J-HToken获取st"><a href="#利用J-HToken获取st" class="headerlink" title="利用J_HToken获取st"></a>利用J_HToken获取st</h2>
                  <p>st也是一个经计算得到的code，可以这么理解，st是淘宝后台利用J_HToken以及其他数据经过计算之后得到的，可以利用st和用户名直接用get方式登录，所以st可以理解为一个秘钥。这个st值只会使用一次，如果第二次用get方式登录则会失效。所以它是一次性使用的。 下面J_HToken计算st的方法如下</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment">#通过token获得st</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getSTbyToken</span><span class="params">(self,token)</span>:</span></span><br><span class="line">    tokenURL = <span class="string">'https://passport.alipay.com/mini_apply_st.js?site=0&amp;token=%s&amp;callback=stCallback6'</span> % token</span><br><span class="line">    request = urllib2.Request(tokenURL)</span><br><span class="line">    response = urllib2.urlopen(request)</span><br><span class="line">    <span class="comment">#处理st，获得用户淘宝主页的登录地址</span></span><br><span class="line">    pattern = re.compile(<span class="string">'&#123;"st":"(.*?)"&#125;'</span>,re.S)</span><br><span class="line">    result = re.search(pattern,response.read())</span><br><span class="line">    <span class="comment">#如果成功匹配</span></span><br><span class="line">    <span class="keyword">if</span> result:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">u"成功获取st码"</span></span><br><span class="line">        <span class="comment">#获取st的值</span></span><br><span class="line">        st = result.group(<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">return</span> st</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">u"未匹配到st"</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="直接利用st登录"><a href="#直接利用st登录" class="headerlink" title="直接利用st登录"></a>直接利用st登录</h2>
                  <p>得到st之后，基本上就大功告成啦，一段辛苦终于没有白费，你可以直接构建get方式请求的URL，直接访问这个URL便可以实现登录。</p>
                  <figure class="highlight gcode">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">stURL = <span class="string">'https://login.taobao.com/member/vst.htm?st=%s&amp;TPL_username=%s'</span> <span class="meta">%</span> <span class="comment">(st,username)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>比如</p>
                  <figure class="highlight vim">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"> http<span class="variable">s:</span>//login.taobao.<span class="keyword">com</span>/member/vst.htm?<span class="keyword">st</span>=<span class="number">1</span>uynJELa4hKfsfWU3OjPJCw&amp;TPL_username=cqcre</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>直接访问该链接即可实现登录，不过我这个应该已经失效了吧~ 代码在这先不贴了，剩下的一起贴了~</p>
                  <h2 id="获取已买到的宝贝页面"><a href="#获取已买到的宝贝页面" class="headerlink" title="获取已买到的宝贝页面"></a>获取已买到的宝贝页面</h2>
                  <p>已买到的宝贝的页面地址是</p>
                  <figure class="highlight awk">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">http:<span class="regexp">//</span>buyer.trade.taobao.com<span class="regexp">/trade/i</span>temlist<span class="regexp">/list_bought_items.htm</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>另外还有页码的参数。 重新构建一个带有cookie的opener，将上面的带有st的URL打开，保存它的cookie，然后再利用这个opener打开已买到的宝贝的页面，你就会得到已买到的宝贝页面详情了。</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment">#获得已买到的宝贝页面</span></span><br><span class="line">def getGoodsPage(self,pageIndex):</span><br><span class="line">    goodsURL = <span class="string">'http://buyer.trade.taobao.com/trade/itemlist/listBoughtItems.htm?action=itemlist/QueryAction&amp;event_submit_do_query=1&amp;pageNum='</span> + str(pageIndex)</span><br><span class="line">    response = self.newOpener.open(goodsURL)</span><br><span class="line">   <span class="built_in"> page </span>=  response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">    return page</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>正则表达式提取信息 这是我的已买到的宝贝界面，审查元素可以看到，每一个宝贝都是tbody标签包围着。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225223302.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225223302.jpg" alt="QQ截图20150225223302"></a>我们现在想获取订单时间，订单号，卖家店铺名称，宝贝名称，原价，购买数量，最后付款多少，交易状态这几个量，具体就不再分析啦，正则表达式还不熟悉的同学请参考前面所说的正则表达式的用法，在这里，正则表达式匹配的代码是</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment">#u'\u8ba2\u5355\u53f7'是订单号的编码</span></span><br><span class="line">pattern = re.compile(<span class="string">u'dealtime.*?&gt;(.*?)&lt;/span&gt;.*?\u8ba2\u5355\u53f7.*?&lt;em&gt;(.*?)&lt;/em&gt;.*?shopname.*?title="(.*?)".*?baobei-name"&gt;.*?&lt;a.*?&gt;(.*?)&lt;/a&gt;.*?'</span></span><br><span class="line">                     <span class="string">u'price.*?title="(.*?)".*?quantity.*?title="(.*?)".*?amount.*?em.*?&gt;(.*?)&lt;/em&gt;.*?trade-status.*?&lt;a.*?&gt;(.*?)&lt;/a&gt;'</span>,re.S)</span><br><span class="line">result = re.findall(pattern,page)</span><br><span class="line"><span class="keyword">for</span> item <span class="keyword">in</span> result:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'------------------------------------------------------------'</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">"购买日期:"</span>,item[<span class="number">0</span>].strip(), <span class="string">'订单号:'</span>,item[<span class="number">1</span>].strip(),<span class="string">'卖家店铺:'</span>,item[<span class="number">2</span>].strip()</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'宝贝名称:'</span>,item[<span class="number">3</span>].strip()</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'原价:'</span>,item[<span class="number">4</span>].strip(),<span class="string">'购买数量:'</span>,item[<span class="number">5</span>].strip(),<span class="string">'实际支付:'</span>,item[<span class="number">6</span>].strip(),<span class="string">'交易状态'</span>,item[<span class="number">7</span>].strip()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="最终代码整理"><a href="#最终代码整理" class="headerlink" title="最终代码整理"></a>最终代码整理</h2>
                  <p>恩，你懂得，最重要的东西来了，经过博主2天多的奋战，代码基本就构建完成。写了两个类，其中提取页面信息的方法我单独放到了一个类中，叫 tool.py，类名为 Tool。 先看一下运行结果吧~ <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225234414.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150225234414.jpg" alt="QQ截图20150225234414"></a> 最终代码如下</p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">tool</span><span class="selector-class">.py</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"><span class="comment">#处理获得的宝贝页面</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tool</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#初始化</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#获得页码数</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPageNum</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        pattern = re.compile(<span class="string">u'&lt;div class="total"&gt;.*?\u5171(.*?)\u9875'</span>,re.S)</span><br><span class="line">        result = re.search(pattern,page)</span><br><span class="line">        <span class="keyword">if</span> result:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">"找到了共多少页"</span></span><br><span class="line">            pageNum = result.group(<span class="number">1</span>).strip()</span><br><span class="line">            <span class="keyword">print</span> <span class="string">'共'</span>,pageNum,<span class="string">'页'</span></span><br><span class="line">            <span class="keyword">return</span> pageNum</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getGoodsInfo</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        <span class="comment">#u'\u8ba2\u5355\u53f7'是订单号的编码</span></span><br><span class="line">        pattern = re.compile(<span class="string">u'dealtime.*?&gt;(.*?)&lt;/span&gt;.*?\u8ba2\u5355\u53f7.*?&lt;em&gt;(.*?)&lt;/em&gt;.*?shopname.*?title="(.*?)".*?baobei-name"&gt;.*?&lt;a.*?&gt;(.*?)&lt;/a&gt;.*?'</span></span><br><span class="line">                             <span class="string">u'price.*?title="(.*?)".*?quantity.*?title="(.*?)".*?amount.*?em.*?&gt;(.*?)&lt;/em&gt;.*?trade-status.*?&lt;a.*?&gt;(.*?)&lt;/a&gt;'</span>,re.S)</span><br><span class="line">        result = re.findall(pattern,page)</span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> result:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">'------------------------------------------------------------'</span></span><br><span class="line">            <span class="keyword">print</span> <span class="string">"购买日期:"</span>,item[<span class="number">0</span>].strip(), <span class="string">'订单号:'</span>,item[<span class="number">1</span>].strip(),<span class="string">'卖家店铺:'</span>,item[<span class="number">2</span>].strip()</span><br><span class="line">            <span class="keyword">print</span> <span class="string">'宝贝名称:'</span>,item[<span class="number">3</span>].strip()</span><br><span class="line">            <span class="keyword">print</span> <span class="string">'原价:'</span>,item[<span class="number">4</span>].strip(),<span class="string">'购买数量:'</span>,item[<span class="number">5</span>].strip(),<span class="string">'实际支付:'</span>,item[<span class="number">6</span>].strip(),<span class="string">'交易状态'</span>,item[<span class="number">7</span>].strip()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">taobao</span><span class="selector-class">.py</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> urllib</span><br><span class="line"><span class="keyword">import</span> urllib2</span><br><span class="line"><span class="keyword">import</span> cookielib</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">import</span> webbrowser</span><br><span class="line"><span class="keyword">import</span> tool</span><br><span class="line"></span><br><span class="line"><span class="comment">#模拟登录淘宝类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Taobao</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#初始化方法</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#登录的URL</span></span><br><span class="line">        self.loginURL = <span class="string">"https://login.taobao.com/member/login.jhtml"</span></span><br><span class="line">        <span class="comment">#代理IP地址，防止自己的IP被封禁</span></span><br><span class="line">        self.proxyURL = <span class="string">'http://120.193.146.97:843'</span></span><br><span class="line">        <span class="comment">#登录POST数据时发送的头部信息</span></span><br><span class="line">        self.loginHeaders =  &#123;</span><br><span class="line">            <span class="string">'Host'</span>:<span class="string">'login.taobao.com'</span>,</span><br><span class="line">            <span class="string">'User-Agent'</span> : <span class="string">'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0'</span>,</span><br><span class="line">            <span class="string">'Referer'</span> : <span class="string">'https://login.taobao.com/member/login.jhtml'</span>,</span><br><span class="line">            <span class="string">'Content-Type'</span>: <span class="string">'application/x-www-form-urlencoded'</span>,</span><br><span class="line">            <span class="string">'Connection'</span> : <span class="string">'Keep-Alive'</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">#用户名</span></span><br><span class="line">        self.username = <span class="string">'cqcre'</span></span><br><span class="line">        <span class="comment">#ua字符串，经过淘宝ua算法计算得出，包含了时间戳,浏览器,屏幕分辨率,随机数,鼠标移动,鼠标点击,其实还有键盘输入记录,鼠标移动的记录、点击的记录等等的信息</span></span><br><span class="line">        self.ua = <span class="string">'191UW5TcyMNYQwiAiwTR3tCf0J/QnhEcUpkMmQ=|Um5Ockt0TXdPc011TXVKdyE=|U2xMHDJ+H2QJZwBxX39Rb1d5WXcrSixAJ1kjDVsN|VGhXd1llXGNaYFhkWmJaYl1gV2pIdUtyTXRKfkN4Qn1FeEF6R31TBQ==|VWldfS0TMw8xDjYWKhAwHiUdOA9wCDEVaxgkATdcNU8iDFoM|VmNDbUMV|V2NDbUMV|WGRYeCgGZhtmH2VScVI2UT5fORtmD2gCawwuRSJHZAFsCWMOdVYyVTpbPR99HWAFYVMpUDUFORshHiQdJR0jAT0JPQc/BDoFPgooFDZtVBR5Fn9VOwt2EWhCOVQ4WSJPJFkHXhgoSDVIMRgnHyFqQ3xEezceIRkmahRqFDZLIkUvRiEDaA9qQ3xEezcZORc5bzk=|WWdHFy0TMw8vEy0UIQE0ADgYJBohGjoAOw4uEiwXLAw2DThuOA==|WmBAED5+KnIbdRh1GXgFQSZbGFdrUm1UblZqVGxQa1ZiTGxQcEp1I3U=|W2NDEz19KXENZwJjHkY7Ui9OJQsre09zSWlXY1oMLBExHzERLxsuE0UT|XGZGFjh4LHQdcx5zH34DRyBdHlFtVGtSaFBsUmpWbVBkSmpXd05zTnMlcw==|XWdHFzl5LXUJYwZnGkI/VitKIQ8vEzMKNws3YTc=|XmdaZ0d6WmVFeUB8XGJaYEB4TGxWbk5yTndXa0tyT29Ta0t1QGBeZDI='</span></span><br><span class="line">        <span class="comment">#密码，在这里不能输入真实密码，淘宝对此密码进行了加密处理，256位，此处为加密后的密码</span></span><br><span class="line">        self.password2 = <span class="string">'7511aa6854629e45de220d29174f1066537a73420ef6dbb5b46f202396703a2d56b0312df8769d886e6ca63d587fdbb99ee73927e8c07d9c88cd02182e1a21edc13fb8e140a4a2a4b53bf38484bd0e08199e03eb9bf7b365a5c673c03407d812b91394f0d3c7564042e3f2b11d156aeea37ad6460118914125ab8f8ac466f'</span></span><br><span class="line">        self.post = post = &#123;</span><br><span class="line">            <span class="string">'ua'</span>:self.ua,</span><br><span class="line">            <span class="string">'TPL_checkcode'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'CtrlVersion'</span>: <span class="string">'1,0,0,7'</span>,</span><br><span class="line">            <span class="string">'TPL_password'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'TPL_redirect_url'</span>:<span class="string">'http://i.taobao.com/my_taobao.htm?nekot=udm8087E1424147022443'</span>,</span><br><span class="line">            <span class="string">'TPL_username'</span>:self.username,</span><br><span class="line">            <span class="string">'loginsite'</span>:<span class="string">'0'</span>,</span><br><span class="line">            <span class="string">'newlogin'</span>:<span class="string">'0'</span>,</span><br><span class="line">            <span class="string">'from'</span>:<span class="string">'tb'</span>,</span><br><span class="line">            <span class="string">'fc'</span>:<span class="string">'default'</span>,</span><br><span class="line">            <span class="string">'style'</span>:<span class="string">'default'</span>,</span><br><span class="line">            <span class="string">'css_style'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'tid'</span>:<span class="string">'XOR_1_000000000000000000000000000000_625C4720470A0A050976770A'</span>,</span><br><span class="line">            <span class="string">'support'</span>:<span class="string">'000001'</span>,</span><br><span class="line">            <span class="string">'loginType'</span>:<span class="string">'4'</span>,</span><br><span class="line">            <span class="string">'minititle'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'minipara'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'umto'</span>:<span class="string">'NaN'</span>,</span><br><span class="line">            <span class="string">'pstrong'</span>:<span class="string">'3'</span>,</span><br><span class="line">            <span class="string">'llnick'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'sign'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'need_sign'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'isIgnore'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'full_redirect'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'popid'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'callback'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'guf'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'not_duplite_str'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'need_user_id'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'poy'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'gvfdcname'</span>:<span class="string">'10'</span>,</span><br><span class="line">            <span class="string">'gvfdcre'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'from_encoding '</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'sub'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'TPL_password_2'</span>:self.password2,</span><br><span class="line">            <span class="string">'loginASR'</span>:<span class="string">'1'</span>,</span><br><span class="line">            <span class="string">'loginASRSuc'</span>:<span class="string">'1'</span>,</span><br><span class="line">            <span class="string">'allp'</span>:<span class="string">''</span>,</span><br><span class="line">            <span class="string">'oslanguage'</span>:<span class="string">'zh-CN'</span>,</span><br><span class="line">            <span class="string">'sr'</span>:<span class="string">'1366*768'</span>,</span><br><span class="line">            <span class="string">'osVer'</span>:<span class="string">'windows|6.1'</span>,</span><br><span class="line">            <span class="string">'naviVer'</span>:<span class="string">'firefox|35'</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">#将POST的数据进行编码转换</span></span><br><span class="line">        self.postData = urllib.urlencode(self.post)</span><br><span class="line">        <span class="comment">#设置代理</span></span><br><span class="line">        self.proxy = urllib2.ProxyHandler(&#123;<span class="string">'http'</span>:self.proxyURL&#125;)</span><br><span class="line">        <span class="comment">#设置cookie</span></span><br><span class="line">        self.cookie = cookielib.LWPCookieJar()</span><br><span class="line">        <span class="comment">#设置cookie处理器</span></span><br><span class="line">        self.cookieHandler = urllib2.HTTPCookieProcessor(self.cookie)</span><br><span class="line">        <span class="comment">#设置登录时用到的opener，它的open方法相当于urllib2.urlopen</span></span><br><span class="line">        self.opener = urllib2.build_opener(self.cookieHandler,self.proxy,urllib2.HTTPHandler)</span><br><span class="line">        <span class="comment">#赋值J_HToken</span></span><br><span class="line">        self.J_HToken = <span class="string">''</span></span><br><span class="line">        <span class="comment">#登录成功时，需要的Cookie</span></span><br><span class="line">        self.newCookie = cookielib.CookieJar()</span><br><span class="line">        <span class="comment">#登陆成功时，需要的一个新的opener</span></span><br><span class="line">        self.newOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.newCookie))</span><br><span class="line">        <span class="comment">#引入工具类</span></span><br><span class="line">        self.tool = tool.Tool()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#得到是否需要输入验证码，这次请求的相应有时会不同，有时需要验证有时不需要</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">needCheckCode</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#第一次登录获取验证码尝试，构建request</span></span><br><span class="line">        request = urllib2.Request(self.loginURL,self.postData,self.loginHeaders)</span><br><span class="line">        <span class="comment">#得到第一次登录尝试的相应</span></span><br><span class="line">        response = self.opener.open(request)</span><br><span class="line">        <span class="comment">#获取其中的内容</span></span><br><span class="line">        content = response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">        <span class="comment">#获取状态吗</span></span><br><span class="line">        status = response.getcode()</span><br><span class="line">        <span class="comment">#状态码为200，获取成功</span></span><br><span class="line">        <span class="keyword">if</span> status == <span class="number">200</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"获取请求成功"</span></span><br><span class="line">            <span class="comment">#\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801这六个字是请输入验证码的utf-8编码</span></span><br><span class="line">            pattern = re.compile(<span class="string">u'\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801'</span>,re.S)</span><br><span class="line">            result = re.search(pattern,content)</span><br><span class="line">            <span class="comment">#如果找到该字符，代表需要输入验证码</span></span><br><span class="line">            <span class="keyword">if</span> result:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"此次安全验证异常，您需要输入验证码"</span></span><br><span class="line">                <span class="keyword">return</span> content</span><br><span class="line">            <span class="comment">#否则不需要</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment">#返回结果直接带有J_HToken字样，表明直接验证通过</span></span><br><span class="line">                tokenPattern = re.compile(<span class="string">'id="J_HToken" value="(.*?)"'</span>)</span><br><span class="line">                tokenMatch = re.search(tokenPattern,content)</span><br><span class="line">                <span class="keyword">if</span> tokenMatch:</span><br><span class="line">                    self.J_HToken = tokenMatch.group(<span class="number">1</span>)</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"此次安全验证通过，您这次不需要输入验证码"</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"获取请求失败"</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#得到验证码图片</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getCheckCode</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        <span class="comment">#得到验证码的图片</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;img id="J_StandardCode_m.*?data-src="(.*?)"'</span>,re.S)</span><br><span class="line">        <span class="comment">#匹配的结果</span></span><br><span class="line">        matchResult = re.search(pattern,page)</span><br><span class="line">        <span class="comment">#已经匹配得到内容，并且验证码图片链接不为空</span></span><br><span class="line">        <span class="keyword">if</span> matchResult <span class="keyword">and</span> matchResult.group(<span class="number">1</span>):</span><br><span class="line">            <span class="keyword">return</span> matchResult.group(<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"没有找到验证码内容"</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#输入验证码，重新请求，如果验证成功，则返回J_HToken</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">loginWithCheckCode</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#提示用户输入验证码</span></span><br><span class="line">        checkcode = raw_input(<span class="string">'请输入验证码:'</span>)</span><br><span class="line">        <span class="comment">#将验证码重新添加到post的数据中</span></span><br><span class="line">        self.post[<span class="string">'TPL_checkcode'</span>] = checkcode</span><br><span class="line">        <span class="comment">#对post数据重新进行编码</span></span><br><span class="line">        self.postData = urllib.urlencode(self.post)</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="comment">#再次构建请求，加入验证码之后的第二次登录尝试</span></span><br><span class="line">            request = urllib2.Request(self.loginURL,self.postData,self.loginHeaders)</span><br><span class="line">            <span class="comment">#得到第一次登录尝试的相应</span></span><br><span class="line">            response = self.opener.open(request)</span><br><span class="line">            <span class="comment">#获取其中的内容</span></span><br><span class="line">            content = response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">            <span class="comment">#检测验证码错误的正则表达式，\u9a8c\u8bc1\u7801\u9519\u8bef 是验证码错误五个字的编码</span></span><br><span class="line">            pattern = re.compile(<span class="string">u'\u9a8c\u8bc1\u7801\u9519\u8bef'</span>,re.S)</span><br><span class="line">            result = re.search(pattern,content)</span><br><span class="line">            <span class="comment">#如果返回页面包括了，验证码错误五个字</span></span><br><span class="line">            <span class="keyword">if</span> result:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"验证码输入错误"</span></span><br><span class="line">                <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="comment">#返回结果直接带有J_HToken字样，说明验证码输入成功，成功跳转到了获取HToken的界面</span></span><br><span class="line">                tokenPattern = re.compile(<span class="string">'id="J_HToken" value="(.*?)"'</span>)</span><br><span class="line">                tokenMatch = re.search(tokenPattern,content)</span><br><span class="line">                <span class="comment">#如果匹配成功，找到了J_HToken</span></span><br><span class="line">                <span class="keyword">if</span> tokenMatch:</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"验证码输入正确"</span></span><br><span class="line">                    self.J_HToken = tokenMatch.group(<span class="number">1</span>)</span><br><span class="line">                    <span class="keyword">return</span> tokenMatch.group(<span class="number">1</span>)</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    <span class="comment">#匹配失败，J_Token获取失败</span></span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"J_Token获取失败"</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">        <span class="keyword">except</span> urllib2.HTTPError, e:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"连接服务器出错，错误原因"</span>,e.reason</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#通过token获得st</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getSTbyToken</span><span class="params">(self,token)</span>:</span></span><br><span class="line">        tokenURL = <span class="string">'https://passport.alipay.com/mini_apply_st.js?site=0&amp;token=%s&amp;callback=stCallback6'</span> % token</span><br><span class="line">        request = urllib2.Request(tokenURL)</span><br><span class="line">        response = urllib2.urlopen(request)</span><br><span class="line">        <span class="comment">#处理st，获得用户淘宝主页的登录地址</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&#123;"st":"(.*?)"&#125;'</span>,re.S)</span><br><span class="line">        result = re.search(pattern,response.read())</span><br><span class="line">        <span class="comment">#如果成功匹配</span></span><br><span class="line">        <span class="keyword">if</span> result:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"成功获取st码"</span></span><br><span class="line">            <span class="comment">#获取st的值</span></span><br><span class="line">            st = result.group(<span class="number">1</span>)</span><br><span class="line">            <span class="keyword">return</span> st</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"未匹配到st"</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#利用st码进行登录,获取重定向网址</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">loginByST</span><span class="params">(self,st,username)</span>:</span></span><br><span class="line">        stURL = <span class="string">'https://login.taobao.com/member/vst.htm?st=%s&amp;TPL_username=%s'</span> % (st,username)</span><br><span class="line">        headers = &#123;</span><br><span class="line">            <span class="string">'User-Agent'</span> : <span class="string">'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0'</span>,</span><br><span class="line">            <span class="string">'Host'</span>:<span class="string">'login.taobao.com'</span>,</span><br><span class="line">            <span class="string">'Connection'</span> : <span class="string">'Keep-Alive'</span></span><br><span class="line">        &#125;</span><br><span class="line">        request = urllib2.Request(stURL,headers = headers)</span><br><span class="line">        response = self.newOpener.open(request)</span><br><span class="line">        content =  response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">        <span class="comment">#检测结果，看是否登录成功</span></span><br><span class="line">        pattern = re.compile(<span class="string">'top.location = "(.*?)"'</span>,re.S)</span><br><span class="line">        match = re.search(pattern,content)</span><br><span class="line">        <span class="keyword">if</span> match:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"登录网址成功"</span></span><br><span class="line">            location = match.group(<span class="number">1</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">"登录失败"</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#获得已买到的宝贝页面</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getGoodsPage</span><span class="params">(self,pageIndex)</span>:</span></span><br><span class="line">        goodsURL = <span class="string">'http://buyer.trade.taobao.com/trade/itemlist/listBoughtItems.htm?action=itemlist/QueryAction&amp;event_submit_do_query=1'</span> + <span class="string">'&amp;pageNum='</span> + str(pageIndex)</span><br><span class="line">        response = self.newOpener.open(goodsURL)</span><br><span class="line">        page =  response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">        <span class="keyword">return</span> page</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取所有已买到的宝贝信息</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getAllGoods</span><span class="params">(self,pageNum)</span>:</span></span><br><span class="line">        <span class="keyword">print</span> <span class="string">u"获取到的商品列表如下"</span></span><br><span class="line">        <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">1</span>,int(pageNum)+<span class="number">1</span>):</span><br><span class="line">            page = self.getGoodsPage(x)</span><br><span class="line">            self.tool.getGoodsInfo(page)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#程序运行主干</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#是否需要验证码，是则得到页面内容，不是则返回False</span></span><br><span class="line">        needResult = self.needCheckCode()</span><br><span class="line">        <span class="comment">#请求获取失败，得到的结果是None</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> needResult ==<span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> needResult == <span class="literal">False</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"您需要手动输入验证码"</span></span><br><span class="line">                checkCode = self.getCheckCode(needResult)</span><br><span class="line">                <span class="comment">#得到了验证码的链接</span></span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">not</span> checkCode == <span class="literal">False</span>:</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"验证码获取成功"</span></span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"请在浏览器中输入您看到的验证码"</span></span><br><span class="line">                    webbrowser.open_new_tab(checkCode)</span><br><span class="line">                    self.loginWithCheckCode()</span><br><span class="line">                <span class="comment">#验证码链接为空，无效验证码</span></span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">u"验证码获取失败，请重试"</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"不需要输入验证码"</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"请求登录页面失败，无法确认是否需要验证码"</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">#判断token是否正常获取到</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.J_HToken:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">"获取Token失败，请重试"</span></span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        <span class="comment">#获取st码</span></span><br><span class="line">        st = self.getSTbyToken(self.J_HToken)</span><br><span class="line">        <span class="comment">#利用st进行登录</span></span><br><span class="line">        result = self.loginByST(st,self.username)</span><br><span class="line">        <span class="keyword">if</span> result:</span><br><span class="line">            <span class="comment">#获得所有宝贝的页面</span></span><br><span class="line">            page = self.getGoodsPage(<span class="number">1</span>)</span><br><span class="line">            pageNum = self.tool.getPageNum(page)</span><br><span class="line">            self.getAllGoods(pageNum)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"登录失败"</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">taobao = Taobao()</span><br><span class="line">taobao.main()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>好啦，运行结果就是上面贴的图片，可以成功获取到自己的商品列表，前提是把你们的 用户名，ua，password2这三个设置好。 以上均为博主亲身所敲，代码写的不好，谨在此贴出和大家一起分享经验~ 小伙伴们试一下吧，希望对大家有帮助~</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-24 00:20:33" itemprop="dateCreated datePublished" datetime="2015-02-24T00:20:33+08:00">2015-02-24</time>
                </span>
                <span id="/1076.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫实战五之模拟登录淘宝并获取所有订单" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>24k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>22 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1070.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> PHP <i class="label-arrow"></i>
                  </a>
                  <a href="/1070.html" class="post-title-link" itemprop="url">WordPress解决修改style.css不生效问题三步走！</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>最近发现WordPress博客在修改style.css样式不能立即生效的问题，根本原因在于服务器开启了.htaccess缓存，不过你总不能直接把这个关掉吧。开启.htaccess缓存还是有很多好处的。</p>
                  <h2 id="我们为什么要设置-htaccess缓存？"><a href="#我们为什么要设置-htaccess缓存？" class="headerlink" title="我们为什么要设置.htaccess缓存？"></a>我们为什么要设置.htaccess缓存？</h2>
                  <p>网站一般不容易变化的都是一些图片，CSS，JS脚本这些可以缓存到本地，设置一个缓存时间，比如30天，这样访客打开你的网站就不会在从网站服务器直接下载这些数据了，而是直接从本地缓存读取这些数据，这样就大大提高了网站加载速度，减少了加载时间。</p>
                  <h2 id="在不修改-htaccess缓存情况下怎样实现修改style-css并且即时生效？"><a href="#在不修改-htaccess缓存情况下怎样实现修改style-css并且即时生效？" class="headerlink" title="在不修改.htaccess缓存情况下怎样实现修改style.css并且即时生效？"></a>在不修改.htaccess缓存情况下怎样实现修改style.css并且即时生效？</h2>
                  <p>经过博主这么多天的探索，总结出了一个”三步走”战略。</p>
                  <h3 id="第一步"><a href="#第一步" class="headerlink" title="第一步"></a>第一步</h3>
                  <p>当然是修改主题下的 style.css 文件，去定制你想要的样式。</p>
                  <h3 id="第二步"><a href="#第二步" class="headerlink" title="第二步"></a>第二步</h3>
                  <p>找到 functions.php 文件，找到类似</p>
                  <figure class="highlight lisp">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">wp_register_style( 'style', get_template_directory_uri().'/style.css',false,<span class="number">25</span>)<span class="comment">;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>这样的代码，这就是加载 style.css 文件的代码，在这里注意最后一个参数，这是一个版本号，在有了这个之后，浏览器中审查元素，你会发现 引入的样式文件带有一个参数，比如，现在我的引入的css文件就是这样子的。因为带有版本号，所以它缓存了这个文件，如果版本号不变更，那么它永远在加载这个版本的 CSS 文件。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150223140857-e1424671815196.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150223140857-e1424671815196.jpg" alt=""></a> 所以，我们的解决方法就是改变后面的这个数字，也就是上述代码的最后一个参数。 修改完style.css 文件之后，将这个数字加一即可。 P.S 如果你修改为之前的数字，那么它可能会加载回曾经的版本，在这里，最好修改一次递增一下这个数字。</p>
                  <h3 id="第三步"><a href="#第三步" class="headerlink" title="第三步"></a>第三步</h3>
                  <p>现在，你刷新网页可能还不会即时生效样式，就找到 WP Super Cache 插件，点击删除缓存，清一下缓存即可。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150223141547.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150223141547.jpg" alt="20150223141547"></a> 如果没有安装这个插件的童鞋，请安装一个吧，很有用的缓存加速插件。 好，以上就是三步走战略来解决修改style.css不生效问题！ 另外，如果你没有修改 style.css 文件，而是单纯在后台设置了一些选项而发现没有生效，只执行第三部即可生效，亲测可用！</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-23 14:16:21" itemprop="dateCreated datePublished" datetime="2015-02-23T14:16:21+08:00">2015-02-23</time>
                </span>
                <span id="/1070.html" class="post-meta-item leancloud_visitors" data-flag-title="WordPress解决修改style.css不生效问题三步走！" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>885</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>1 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1052.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/1052.html" class="post-title-link" itemprop="url">Python2爬虫学习系列教程</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p><strong>年度重磅大放送！！！博主录制的《Python3网络爬虫实战案例》视频教程及《Python3网络爬虫开发实战》书籍出炉啦！！！欢迎大家支持！！！</strong> 视频教程介绍：<a href="//cuiqingcai.com/4320.html">Python3爬虫视频学习教程</a> 视频教程链接：<a href="//edu.hellobi.com/course/157" target="_blank" rel="noopener">自己动手，丰衣足食！Python3网络爬虫实战案例</a> 书籍内容查看：<a href="//cuiqingcai.com/5052.html">Python3网络爬虫开发实战教程</a> 以下为Python2爬虫系列教程： 大家好哈，我呢最近在学习Python爬虫，感觉非常有意思，真的让生活可以方便很多。学习过程中我把一些学习的笔记总结下来，还记录了一些自己实际写的一些小爬虫，在这里跟大家一同分享，希望对Python爬虫感兴趣的童鞋有帮助，如果有机会期待与大家的交流。</p>
                  <h2 id="一、爬虫入门"><a href="#一、爬虫入门" class="headerlink" title="一、爬虫入门"></a>一、爬虫入门</h2>
                  <ol>
                    <li><a href="//cuiqingcai.com/927.html" title="Python爬虫入门一之综述">Python爬虫入门一之综述</a> 2. <a href="//cuiqingcai.com/942.html" title="Python爬虫入门二之爬虫基础了解">Python爬虫入门二之爬虫基础了解</a> 3. <a href="//cuiqingcai.com/947.html" title="Python爬虫入门三之Urllib库的基本使用">Python爬虫入门三之Urllib库的基本使用</a> 4. <a href="//cuiqingcai.com/954.html" title="Python爬虫入门四之Urllib库的高级用法">Python爬虫入门四之Urllib库的高级用法</a> 5. <a href="//cuiqingcai.com/961.html" title="Python爬虫入门五之URLError异常处理">Python爬虫入门五之URLError异常处理</a> 6. <a href="//cuiqingcai.com/968.html" title="Python爬虫入门六之Cookie的使用">Python爬虫入门六之Cookie的使用</a> 7. <a href="//cuiqingcai.com/977.html" title="Python爬虫入门七之正则表达式">Python爬虫入门七之正则表达式</a></li>
                  </ol>
                  <h2 id="二、爬虫实战"><a href="#二、爬虫实战" class="headerlink" title="二、爬虫实战"></a>二、爬虫实战</h2>
                  <ol>
                    <li><a href="//cuiqingcai.com/990.html" title="Python爬虫实战一之爬取糗事百科段子">Python爬虫实战一之爬取糗事百科段子</a> 2. <a href="//cuiqingcai.com/993.html" title="Python爬虫实战二之爬取百度贴吧帖子">Python爬虫实战二之爬取百度贴吧帖子</a> 3. <a href="//cuiqingcai.com/2083.html">Python爬虫实战三之实现山东大学无线网络掉线自动重连</a> 4. <a href="//cuiqingcai.com/1001.html" title="Python爬虫实战四之抓取淘宝MM照片">Python爬虫实战四之抓取淘宝MM照片</a> 5. <a href="//cuiqingcai.com/1076.html" title="Python爬虫实战五之模拟登录淘宝并获取所有订单">Python爬虫实战五之模拟登录淘宝并获取所有订单</a> 6. <a href="//cuiqingcai.com/1972.html" title="Python爬虫实战六之抓取爱问知识人问题并保存至数据库">Python爬虫实战六之抓取爱问知识人问题并保存至数据库</a> 7. <a href="//cuiqingcai.com/997.html" title="Python爬虫实战七之计算大学本学期绩点">Python爬虫实战七之计算大学本学期绩点</a> 8. <a href="//cuiqingcai.com/2852.html">Python爬虫实战八之利用Selenium抓取淘宝匿名旺旺</a></li>
                  </ol>
                  <h2 id="三、爬虫利器"><a href="#三、爬虫利器" class="headerlink" title="三、爬虫利器"></a>三、爬虫利器</h2>
                  <ol>
                    <li><a href="//cuiqingcai.com/2556.html" title="Python爬虫利器一之Requests库的用法">Python爬虫利器一之Requests库的用法</a> 2. <a href="//cuiqingcai.com/1319.html" title="Python爬虫利器二之Beautiful Soup的用法">Python爬虫利器二之Beautiful Soup的用法</a> 3. <a href="//cuiqingcai.com/2621.html" title="Python爬虫利器三之Xpath语法与lxml库的用法">Python爬虫利器三之Xpath语法与lxml库的用法</a> 4. <a href="//cuiqingcai.com/2577.html" title="Python爬虫利器四之PhantomJS的用法">Python爬虫利器四之PhantomJS的用法</a> 5. <a href="//cuiqingcai.com/2599.html" title="Python爬虫利器五之Selenium的用法">Python爬虫利器五之Selenium的用法</a> 6. <a href="//cuiqingcai.com/2636.html" title="Python爬虫利器六之PyQuery的用法">Python爬虫利器六之PyQuery的用法</a></li>
                  </ol>
                  <h2 id="四、爬虫进阶"><a href="#四、爬虫进阶" class="headerlink" title="四、爬虫进阶"></a>四、爬虫进阶</h2>
                  <ol>
                    <li><a href="//cuiqingcai.com/2433.html" title="Python爬虫进阶一之爬虫框架概述">Python爬虫进阶一之爬虫框架概述</a> 2. <a href="//cuiqingcai.com/2443.html" title="Python爬虫进阶二之PySpider框架安装配置">Python爬虫进阶二之PySpider框架安装配置</a> 3. <a href="//cuiqingcai.com/912.html" title="Python爬虫进阶三之爬虫框架Scrapy安装配置">Python爬虫进阶三之爬虫框架Scrapy安装配置</a> 4. <a href="//cuiqingcai.com/2652.html" title="Python爬虫进阶四之PySpider的用法">Python爬虫进阶四之PySpider的用法</a> 5. <a href="//cuiqingcai.com/3325.html" title="Python爬虫进阶五之多线程的用法">Python爬虫进阶五之多线程的用法</a> 6. <a href="//cuiqingcai.com/3335.html" title="Python爬虫进阶六之多进程的用法">Python爬虫进阶六之多进程的用法</a> 7. <a href="//cuiqingcai.com/3443.html" title="Python爬虫进阶七之设置ADSL拨号服务器代理">Python爬虫进阶七之设置ADSL拨号服务器代理</a> 目前暂时是这些文章，随着学习的进行，会不断更新哒，敬请期待~ 希望对大家有所帮助，谢谢！</li>
                  </ol>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-21 14:14:48" itemprop="dateCreated datePublished" datetime="2015-02-21T14:14:48+08:00">2015-02-21</time>
                </span>
                <span id="/1052.html" class="post-meta-item leancloud_visitors" data-flag-title="Python2爬虫学习系列教程" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>1k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>1 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/1001.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/1001.html" class="post-title-link" itemprop="url">Python爬虫实战四之抓取淘宝MM照片</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>福利啊福利，本次为大家带来的项目是抓取淘宝MM照片并保存起来，大家有没有很激动呢？</p>
                  <h2 id="最新动态"><a href="#最新动态" class="headerlink" title="最新动态"></a>最新动态</h2>
                  <blockquote>
                    <p>更新时间：2015/8/2 最近好多读者反映代码已经不能用了，原因是淘宝索引页的MM链接改了。网站改版了，URL的索引已经和之前的不一样了，之前可以直接跳转到每个MM的个性域名，现在中间加了一个跳转页，本以为可以通过这个页面然后跳转到原来的个性域名，而经过一番折腾发现，这个跳转页中的内容是JS动态生成的，所以不能用Urllib库来直接抓取了，本篇就只提供学习思路，代码不能继续用了。 之后博主会利用其它方法来尝试解决，如果解决，第一时间更新！谢谢大家！</p>
                    <p>更新时间：2016/3/26 如上问题已解决，利用 PhantomJS的动态解析即可完成。因为 PySpider 同样支持 PhantomJS，所以我直接利用了 PySpider 来完成，解决方案如下 <a href="http://cuiqingcai.com/2652.html">解决方案</a> 另外如果不想使用框架，可以直接利用 Selenium + PhantomJS 来解析，同样方便，解决方案可以参考 <a href="http://cuiqingcai.com/2599.html">动态解析解决方案</a></p>
                  </blockquote>
                  <h2 id="本篇目标"><a href="#本篇目标" class="headerlink" title="本篇目标"></a>本篇目标</h2>
                  <p>1.抓取淘宝MM的姓名，头像，年龄 2.抓取每一个MM的资料简介以及写真图片 3.把每一个MM的写真图片按照文件夹保存到本地 4.熟悉文件保存的过程</p>
                  <h2 id="1-URL的格式"><a href="#1-URL的格式" class="headerlink" title="1.URL的格式"></a>1.URL的格式</h2>
                  <p>在这里我们用到的URL是 <a href="http://mm.taobao.com/json/request_top_list.htm?page=1" target="_blank" rel="noopener">http://mm.taobao.com/json/request_top_list.htm?page=1</a>，问号前面是基地址，后面的参数page是代表第几页，可以随意更换地址。点击开之后，会发现有一些淘宝MM的简介，并附有超链接链接到个人详情页面。 我们需要抓取本页面的头像地址，MM姓名，MM年龄，MM居住地，以及MM的个人详情页面地址。</p>
                  <h2 id="2-抓取简要信息"><a href="#2-抓取简要信息" class="headerlink" title="2.抓取简要信息"></a>2.抓取简要信息</h2>
                  <p>相信大家经过上几次的实战，对抓取和提取页面的地址已经非常熟悉了，这里没有什么难度了，我们首先抓取本页面的MM详情页面地址，姓名，年龄等等的信息打印出来，直接贴代码如下</p>
                  <figure class="highlight ruby">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author_<span class="number">_</span> = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line">import re</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Spider</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">self</span>.siteURL = <span class="string">'http://mm.taobao.com/json/request_top_list.htm'</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(<span class="keyword">self</span>,pageIndex)</span></span><span class="symbol">:</span></span><br><span class="line">        url = <span class="keyword">self</span>.siteURL + <span class="string">"?page="</span> + str(pageIndex)</span><br><span class="line">        print url</span><br><span class="line">        request = urllib2.Request(url)</span><br><span class="line">        response = urllib2.urlopen(request)</span><br><span class="line">        <span class="keyword">return</span> response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getContents</span><span class="params">(<span class="keyword">self</span>,pageIndex)</span></span><span class="symbol">:</span></span><br><span class="line">        page = <span class="keyword">self</span>.getPage(pageIndex)</span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;div class="list-item".*?pic-word.*?&lt;a href="(.*?)".*?&lt;img src="(.*?)".*?&lt;a class="lady-name.*?&gt;(.*?)&lt;/a&gt;.*?&lt;strong&gt;(.*?)&lt;/strong&gt;.*?&lt;span&gt;(.*?)&lt;/span&gt;'</span>,re.S)</span><br><span class="line">        items = re.findall(pattern,page)</span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> <span class="symbol">items:</span></span><br><span class="line">            print item[<span class="number">0</span>],item[<span class="number">1</span>],item[<span class="number">2</span>],item[<span class="number">3</span>],item[<span class="number">4</span>]</span><br><span class="line"></span><br><span class="line">spider = Spider()</span><br><span class="line">spider.getContents(<span class="number">1</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果如下 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220234132.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220234132.jpg" alt="QQ截图20150220234132"></a></p>
                  <h2 id="2-文件写入简介"><a href="#2-文件写入简介" class="headerlink" title="2.文件写入简介"></a>2.文件写入简介</h2>
                  <p>在这里，我们有写入图片和写入文本两种方式</p>
                  <h3 id="1）写入图片"><a href="#1）写入图片" class="headerlink" title="1）写入图片"></a>1）写入图片</h3>
                  <figure class="highlight sas">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">#传入图片地址，文件名，保存单张图片</span><br><span class="line">def saveImg(self,imageURL,<span class="meta">fileName</span>):</span><br><span class="line">     u = urllib.ur<span class="meta">lopen(</span>imageURL)</span><br><span class="line"><span class="keyword">     data </span>= u.read()</span><br><span class="line">     f =<span class="meta"> open(</span><span class="meta">fileName</span>, <span class="string">'wb'</span>)</span><br><span class="line">     f.write(data)</span><br><span class="line">     f<span class="meta">.close(</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="2）写入文本"><a href="#2）写入文本" class="headerlink" title="2）写入文本"></a>2）写入文本</h3>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">saveBrief</span><span class="params">(self,content,name)</span>:</span></span><br><span class="line">    fileName = name + <span class="string">"/"</span> + name + <span class="string">".txt"</span></span><br><span class="line">    f = open(fileName,<span class="string">"w+"</span>)</span><br><span class="line">    <span class="keyword">print</span> <span class="string">u"正在偷偷保存她的个人信息为"</span>,fileName</span><br><span class="line">    f.write(content.encode(<span class="string">'utf-8'</span>))</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="3）创建新目录"><a href="#3）创建新目录" class="headerlink" title="3）创建新目录"></a>3）创建新目录</h3>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment">#创建新目录</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mkdir</span><span class="params">(self,path)</span>:</span></span><br><span class="line">    path = path.strip()</span><br><span class="line">    <span class="comment"># 判断路径是否存在</span></span><br><span class="line">    <span class="comment"># 存在     True</span></span><br><span class="line">    <span class="comment"># 不存在   False</span></span><br><span class="line">    isExists=os.path.exists(path)</span><br><span class="line">    <span class="comment"># 判断结果</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> isExists:</span><br><span class="line">        <span class="comment"># 如果不存在则创建目录</span></span><br><span class="line">        <span class="comment"># 创建目录操作函数</span></span><br><span class="line">        os.makedirs(path)</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="comment"># 如果目录存在则不创建，并提示目录已存在</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">False</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="3-代码完善"><a href="#3-代码完善" class="headerlink" title="3.代码完善"></a>3.代码完善</h2>
                  <p>主要的知识点已经在前面都涉及到了，如果大家前面的章节都已经看了，完成这个爬虫不在话下，具体的详情在此不再赘述，直接帖代码啦。</p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">spider</span><span class="selector-class">.py</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> urllib</span><br><span class="line"><span class="keyword">import</span> urllib2</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">import</span> tool</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="comment">#抓取MM</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Spider</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#页面初始化</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.siteURL = <span class="string">'http://mm.taobao.com/json/request_top_list.htm'</span></span><br><span class="line">        self.tool = tool.Tool()</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取索引页面的内容</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(self,pageIndex)</span>:</span></span><br><span class="line">        url = self.siteURL + <span class="string">"?page="</span> + str(pageIndex)</span><br><span class="line">        request = urllib2.Request(url)</span><br><span class="line">        response = urllib2.urlopen(request)</span><br><span class="line">        <span class="keyword">return</span> response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取索引界面所有MM的信息，list格式</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getContents</span><span class="params">(self,pageIndex)</span>:</span></span><br><span class="line">        page = self.getPage(pageIndex)</span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;div class="list-item".*?pic-word.*?&lt;a href="(.*?)".*?&lt;img src="(.*?)".*?&lt;a class="lady-name.*?&gt;(.*?)&lt;/a&gt;.*?&lt;strong&gt;(.*?)&lt;/strong&gt;.*?&lt;span&gt;(.*?)&lt;/span&gt;'</span>,re.S)</span><br><span class="line">        items = re.findall(pattern,page)</span><br><span class="line">        contents = []</span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> items:</span><br><span class="line">            contents.append([item[<span class="number">0</span>],item[<span class="number">1</span>],item[<span class="number">2</span>],item[<span class="number">3</span>],item[<span class="number">4</span>]])</span><br><span class="line">        <span class="keyword">return</span> contents</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取MM个人详情页面</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getDetailPage</span><span class="params">(self,infoURL)</span>:</span></span><br><span class="line">        response = urllib2.urlopen(infoURL)</span><br><span class="line">        <span class="keyword">return</span> response.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取个人文字简介</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getBrief</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;div class="mm-aixiu-content".*?&gt;(.*?)&lt;!--'</span>,re.S)</span><br><span class="line">        result = re.search(pattern,page)</span><br><span class="line">        <span class="keyword">return</span> self.tool.replace(result.group(<span class="number">1</span>))</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取页面所有图片</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getAllImg</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;div class="mm-aixiu-content".*?&gt;(.*?)&lt;!--'</span>,re.S)</span><br><span class="line">        <span class="comment">#个人信息页面所有代码</span></span><br><span class="line">        content = re.search(pattern,page)</span><br><span class="line">        <span class="comment">#从代码中提取图片</span></span><br><span class="line">        patternImg = re.compile(<span class="string">'&lt;img.*?src="(.*?)"'</span>,re.S)</span><br><span class="line">        images = re.findall(patternImg,content.group(<span class="number">1</span>))</span><br><span class="line">        <span class="keyword">return</span> images</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#保存多张写真图片</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">saveImgs</span><span class="params">(self,images,name)</span>:</span></span><br><span class="line">        number = <span class="number">1</span></span><br><span class="line">        <span class="keyword">print</span> <span class="string">u"发现"</span>,name,<span class="string">u"共有"</span>,len(images),<span class="string">u"张照片"</span></span><br><span class="line">        <span class="keyword">for</span> imageURL <span class="keyword">in</span> images:</span><br><span class="line">            splitPath = imageURL.split(<span class="string">'.'</span>)</span><br><span class="line">            fTail = splitPath.pop()</span><br><span class="line">            <span class="keyword">if</span> len(fTail) &gt; <span class="number">3</span>:</span><br><span class="line">                fTail = <span class="string">"jpg"</span></span><br><span class="line">            fileName = name + <span class="string">"/"</span> + str(number) + <span class="string">"."</span> + fTail</span><br><span class="line">            self.saveImg(imageURL,fileName)</span><br><span class="line">            number += <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 保存头像</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">saveIcon</span><span class="params">(self,iconURL,name)</span>:</span></span><br><span class="line">        splitPath = iconURL.split(<span class="string">'.'</span>)</span><br><span class="line">        fTail = splitPath.pop()</span><br><span class="line">        fileName = name + <span class="string">"/icon."</span> + fTail</span><br><span class="line">        self.saveImg(iconURL,fileName)</span><br><span class="line"></span><br><span class="line">    <span class="comment">#保存个人简介</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">saveBrief</span><span class="params">(self,content,name)</span>:</span></span><br><span class="line">        fileName = name + <span class="string">"/"</span> + name + <span class="string">".txt"</span></span><br><span class="line">        f = open(fileName,<span class="string">"w+"</span>)</span><br><span class="line">        <span class="keyword">print</span> <span class="string">u"正在偷偷保存她的个人信息为"</span>,fileName</span><br><span class="line">        f.write(content.encode(<span class="string">'utf-8'</span>))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#传入图片地址，文件名，保存单张图片</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">saveImg</span><span class="params">(self,imageURL,fileName)</span>:</span></span><br><span class="line">         u = urllib.urlopen(imageURL)</span><br><span class="line">         data = u.read()</span><br><span class="line">         f = open(fileName, <span class="string">'wb'</span>)</span><br><span class="line">         f.write(data)</span><br><span class="line">         <span class="keyword">print</span> <span class="string">u"正在悄悄保存她的一张图片为"</span>,fileName</span><br><span class="line">         f.close()</span><br><span class="line"></span><br><span class="line">    <span class="comment">#创建新目录</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">mkdir</span><span class="params">(self,path)</span>:</span></span><br><span class="line">        path = path.strip()</span><br><span class="line">        <span class="comment"># 判断路径是否存在</span></span><br><span class="line">        <span class="comment"># 存在     True</span></span><br><span class="line">        <span class="comment"># 不存在   False</span></span><br><span class="line">        isExists=os.path.exists(path)</span><br><span class="line">        <span class="comment"># 判断结果</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> isExists:</span><br><span class="line">            <span class="comment"># 如果不存在则创建目录</span></span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"偷偷新建了名字叫做"</span>,path,<span class="string">u'的文件夹'</span></span><br><span class="line">            <span class="comment"># 创建目录操作函数</span></span><br><span class="line">            os.makedirs(path)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 如果目录存在则不创建，并提示目录已存在</span></span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"名为"</span>,path,<span class="string">'的文件夹已经创建成功'</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#将一页淘宝MM的信息保存起来</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">savePageInfo</span><span class="params">(self,pageIndex)</span>:</span></span><br><span class="line">        <span class="comment">#获取第一页淘宝MM列表</span></span><br><span class="line">        contents = self.getContents(pageIndex)</span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> contents:</span><br><span class="line">            <span class="comment">#item[0]个人详情URL,item[1]头像URL,item[2]姓名,item[3]年龄,item[4]居住地</span></span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"发现一位模特,名字叫"</span>,item[<span class="number">2</span>],<span class="string">u"芳龄"</span>,item[<span class="number">3</span>],<span class="string">u",她在"</span>,item[<span class="number">4</span>]</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"正在偷偷地保存"</span>,item[<span class="number">2</span>],<span class="string">"的信息"</span></span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"又意外地发现她的个人地址是"</span>,item[<span class="number">0</span>]</span><br><span class="line">            <span class="comment">#个人详情页面的URL</span></span><br><span class="line">            detailURL = item[<span class="number">0</span>]</span><br><span class="line">            <span class="comment">#得到个人详情页面代码</span></span><br><span class="line">            detailPage = self.getDetailPage(detailURL)</span><br><span class="line">            <span class="comment">#获取个人简介</span></span><br><span class="line">            brief = self.getBrief(detailPage)</span><br><span class="line">            <span class="comment">#获取所有图片列表</span></span><br><span class="line">            images = self.getAllImg(detailPage)</span><br><span class="line">            self.mkdir(item[<span class="number">2</span>])</span><br><span class="line">            <span class="comment">#保存个人简介</span></span><br><span class="line">            self.saveBrief(brief,item[<span class="number">2</span>])</span><br><span class="line">            <span class="comment">#保存头像</span></span><br><span class="line">            self.saveIcon(item[<span class="number">1</span>],item[<span class="number">2</span>])</span><br><span class="line">            <span class="comment">#保存图片</span></span><br><span class="line">            self.saveImgs(images,item[<span class="number">2</span>])</span><br><span class="line"></span><br><span class="line">    <span class="comment">#传入起止页码，获取MM图片</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">savePagesInfo</span><span class="params">(self,start,end)</span>:</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(start,end+<span class="number">1</span>):</span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"正在偷偷寻找第"</span>,i,<span class="string">u"个地方，看看MM们在不在"</span></span><br><span class="line">            self.savePageInfo(i)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#传入起止页码即可，在此传入了2,10,表示抓取第2到10页的MM</span></span><br><span class="line">spider = Spider()</span><br><span class="line">spider.savePagesInfo(<span class="number">2</span>,<span class="number">10</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="selector-tag">tool</span><span class="selector-class">.py</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <figure class="highlight vbnet">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="comment">'CQC'</span></span><br><span class="line"><span class="meta">#-*- coding:utf-8 -*-</span></span><br><span class="line">import re</span><br><span class="line"></span><br><span class="line"><span class="meta">#处理页面标签类</span></span><br><span class="line"><span class="keyword">class</span> Tool:</span><br><span class="line">    <span class="meta">#去除img标签,1-7位空格,&amp;nbsp;</span></span><br><span class="line">    removeImg = re.compile(<span class="comment">'<span class="doctag">&lt;img.*?&gt;</span>| &#123;1,7&#125;|&amp;nbsp;')</span></span><br><span class="line">    <span class="meta">#删除超链接标签</span></span><br><span class="line">    removeAddr = re.compile(<span class="comment">'<span class="doctag">&lt;a.*?&gt;</span>|<span class="doctag">&lt;/a&gt;</span>')</span></span><br><span class="line">    <span class="meta">#把换行的标签换为\n</span></span><br><span class="line">    replaceLine = re.compile(<span class="comment">'<span class="doctag">&lt;tr&gt;</span>|<span class="doctag">&lt;div&gt;</span>|<span class="doctag">&lt;/div&gt;</span>|<span class="doctag">&lt;/p&gt;</span>')</span></span><br><span class="line">    <span class="meta">#将表格制表&lt;td&gt;替换为\t</span></span><br><span class="line">    replaceTD= re.compile(<span class="comment">'<span class="doctag">&lt;td&gt;</span>')</span></span><br><span class="line">    <span class="meta">#将换行符或双换行符替换为\n</span></span><br><span class="line">    replaceBR = re.compile(<span class="comment">'<span class="doctag">&lt;br&gt;</span><span class="doctag">&lt;br&gt;</span>|<span class="doctag">&lt;br&gt;</span>')</span></span><br><span class="line">    <span class="meta">#将其余标签剔除</span></span><br><span class="line">    removeExtraTag = re.compile(<span class="comment">'<span class="doctag">&lt;.*?&gt;</span>')</span></span><br><span class="line">    <span class="meta">#将多行空行删除</span></span><br><span class="line">    removeNoneLine = re.compile(<span class="comment">'\n+')</span></span><br><span class="line">    def replace(self,x):</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.removeImg,<span class="string">""</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.removeAddr,<span class="string">""</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.replaceLine,<span class="string">"\n"</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.replaceTD,<span class="string">"\t"</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.replaceBR,<span class="string">"\n"</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.removeExtraTag,<span class="string">""</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.removeNoneLine,<span class="string">"\n"</span>,x)</span><br><span class="line">        <span class="meta">#strip()将前后多余内容删除</span></span><br><span class="line">        <span class="keyword">return</span> x.strip()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>以上两个文件就是所有的代码内容，运行一下试试看，那叫一个酸爽啊 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150221020543.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150221020543.jpg" alt="QQ截图20150221020543"></a> 看看文件夹里面有什么变化 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150221020709.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150221020709.jpg" alt="QQ截图20150221020709"></a> <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150221021032.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150221021032.jpg" alt="QQ截图20150221021032"></a> 不知不觉，海量的MM图片已经进入了你的电脑，还不快快去试试看！！ 代码均为本人所敲，写的不好，大神勿喷，写来方便自己，同时分享给大家参考！希望大家支持！</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-20 22:48:11" itemprop="dateCreated datePublished" datetime="2015-02-20T22:48:11+08:00">2015-02-20</time>
                </span>
                <span id="/1001.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫实战四之抓取淘宝MM照片" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>6.6k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>6 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/997.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/997.html" class="post-title-link" itemprop="url">Python爬虫实战七之计算大学本学期绩点</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>大家好，本次为大家带来的项目是计算大学本学期绩点。首先说明的是，博主来自山东大学，有属于个人的学生成绩管理系统，需要学号密码才可以登录，不过可能广大读者没有这个学号密码，不能实际进行操作，所以最主要的还是获取它的原理。最主要的是了解cookie的相关操作。</p>
                  <h2 id="本篇目标"><a href="#本篇目标" class="headerlink" title="本篇目标"></a>本篇目标</h2>
                  <p>1.模拟登录学生成绩管理系统 2.抓取本学期成绩界面 3.计算打印本学期成绩</p>
                  <h2 id="1-URL的获取"><a href="#1-URL的获取" class="headerlink" title="1.URL的获取"></a>1.URL的获取</h2>
                  <p>恩，博主来自山东大学~ 先贴一个URL，让大家知道我们学校学生信息系统的网站构架，主页是 <a href="http://jwxt.sdu.edu.cn:7890/zhxt_bks/zhxt_bks.html" target="_blank" rel="noopener">http://jwxt.sdu.edu.cn:7890/zhxt_bks/zhxt_bks.html</a>，山东大学学生个人信息系统，进去之后，Oh不，他竟然用了frame，一个多么古老的而又任性的写法，真是惊出一身冷汗~ 算了，就算他是frame又能拿我怎么样？我们点到登录界面，审查一下元素，先看看登录界面的URL是怎样的？ <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220211218.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220211218.jpg" alt="QQ截图20150220211218"></a> 恩，看到了右侧的frame名称，src=”xk_login.html”，可以分析出完整的登录界面的网址为 <a href="http://jwxt.sdu.edu.cn:7890/zhxt_bks/xk_login.html" target="_blank" rel="noopener">http://jwxt.sdu.edu.cn:7890/zhxt_bks/xk_login.html</a>，点进去看看，真是棒棒哒，他喵的竟然是清华大学选课系统，醉了，你说你抄袭就抄袭吧，改改名字也不错啊~ 算了，就不和他计较了。现在，我们登录一下，用浏览器监听网络。 我用的是猎豹浏览器，审查元素时会有一个网络的选项，如果大家用的Chrome，也有相对应的功能，Firefox需要装插件HttpFox，同样可以实现。 这个网络监听功能可以监听表单的传送以及请求头，响应头等等的信息。截个图看一下，恩，我偷偷把密码隐藏了，你看不到~ 大家看到的是登录之后出现的信息以及NetWork监听，显示了hearders的详细信息。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220212025.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220212025.jpg" alt="QQ截图20150220212025"></a> 最主要的内容，我们可以发现有一个表单提交的过程，提交方式为POST，两个参数分别为stuid和pwd。 请求的URL为 <a href="http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login" target="_blank" rel="noopener">http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login</a>，没错，找到表单数据和目标地址就是这么简单。 在这里注意，刚才的 <a href="http://jwxt.sdu.edu.cn:7890/zhxt_bks/xk_login.html" target="_blank" rel="noopener">http://jwxt.sdu.edu.cn:7890/zhxt_bks/xk_login.html</a> 只是登录界面的地址，刚刚得到的这个地址才是登录索要提交到的真正的URL。希望大家这里不要混淆。 不知道山大这个系统有没有做headers的检查，我们先不管这么多，先尝试一下模拟登录并保存Cookie。</p>
                  <h2 id="2-模拟登录"><a href="#2-模拟登录" class="headerlink" title="2.模拟登录"></a>2.模拟登录</h2>
                  <p>好，通过以上信息，我们已经找到了登录的目标地址为 <a href="http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login" target="_blank" rel="noopener">http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login</a> 有一个表单提交到这个URL，表单的两个内容分别为stuid和pwd，学号和密码，没有其他的隐藏信息，提交方式为POST。 好，现在我们首先构造以下代码来完成登录。看看会不会获取到登录之后的提示页面。</p>
                  <figure class="highlight ruby">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author_<span class="number">_</span> = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line">import cookielib</span><br><span class="line">import re</span><br><span class="line"></span><br><span class="line"><span class="comment">#山东大学绩点运算</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SDU</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">self</span>.loginUrl = <span class="string">'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login'</span></span><br><span class="line">        <span class="keyword">self</span>.cookies = cookielib.CookieJar()</span><br><span class="line">        <span class="keyword">self</span>.postdata = urllib.urlencode(&#123;</span><br><span class="line">            <span class="string">'stuid'</span><span class="symbol">:<span class="string">'201200131012'</span></span>,</span><br><span class="line">            <span class="string">'pwd'</span><span class="symbol">:<span class="string">'xxxxxx'</span></span></span><br><span class="line">         &#125;)</span><br><span class="line">        <span class="keyword">self</span>.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(<span class="keyword">self</span>.cookies))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        request  = urllib2.Request(</span><br><span class="line">            url = <span class="keyword">self</span>.loginUrl,</span><br><span class="line">            data = <span class="keyword">self</span>.postdata)</span><br><span class="line">        result = <span class="keyword">self</span>.opener.open(request)</span><br><span class="line">        <span class="comment">#打印登录内容</span></span><br><span class="line">        print result.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">sdu = SDU()</span><br><span class="line">sdu.getPage()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>测试一下，竟然成功了，山大这网竟然没有做headers检查，很顺利就登录进去了。 说明一下，在这里我们利用了前面所说的cookie，用到了CookieJar这个对象来保存cookies，另外通过构建opener，利用open方法实现了登录。如果大家觉得这里有疑惑，请看 <a href="http://cuiqingcai.com/968.html">Python爬虫入门六之Cookie的使用</a>，这篇文章说得比较详细。 好，我们看一下运行结果 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220214238.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220214238.jpg" alt="QQ截图20150220214238"></a> 酸爽啊，接下来我们只要再获取到本学期成绩界面然后把成绩抓取出来就好了。</p>
                  <h2 id="3-抓取本学期成绩"><a href="#3-抓取本学期成绩" class="headerlink" title="3.抓取本学期成绩"></a>3.抓取本学期成绩</h2>
                  <p>让我们先在浏览器中找到本学期成绩界面，点击左边的本学期成绩。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220220000.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220220000.jpg" alt="QQ截图20150220220000"></a> 重新审查元素，你会发现这个frame的src还是没有变，仍然是xk_login.html，引起这个页面变化的原因是在左边的本学期成绩这个超链接设置了一个目标frame，所以，那个页面就显示在右侧了。 所以，让我们再审查一下本学期成绩这个超链接的内容是什么~ <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220220338.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220220338.jpg" alt="QQ截图20150220220338"></a> 恩，找到它了，<a href="/pls/wwwbks/bkscjcx.curscopre" target="w_right">本学期成绩</a> 那么，完整的URL就是 <a href="http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bkscjcx.curscopre" target="_blank" rel="noopener">http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bkscjcx.curscopre</a>，好，URL已经找到了，我们继续完善一下代码，获取这个页面。</p>
                  <figure class="highlight ruby">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author_<span class="number">_</span> = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"></span><br><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line">import cookielib</span><br><span class="line">import re</span><br><span class="line"></span><br><span class="line"><span class="comment">#山东大学绩点运算</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SDU</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="comment">#登录URL</span></span><br><span class="line">        <span class="keyword">self</span>.loginUrl = <span class="string">'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login'</span></span><br><span class="line">        <span class="comment">#本学期成绩URL</span></span><br><span class="line">        <span class="keyword">self</span>.gradeUrl = <span class="string">'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bkscjcx.curscopre'</span></span><br><span class="line">        <span class="keyword">self</span>.cookies = cookielib.CookieJar()</span><br><span class="line">        <span class="keyword">self</span>.postdata = urllib.urlencode(&#123;</span><br><span class="line">            <span class="string">'stuid'</span><span class="symbol">:<span class="string">'201200131012'</span></span>,</span><br><span class="line">            <span class="string">'pwd'</span><span class="symbol">:<span class="string">'xxxxxx'</span></span></span><br><span class="line">         &#125;)</span><br><span class="line">        <span class="comment">#构建opener</span></span><br><span class="line">        <span class="keyword">self</span>.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(<span class="keyword">self</span>.cookies))</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取本学期成绩页面</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        request  = urllib2.Request(</span><br><span class="line">            url = <span class="keyword">self</span>.loginUrl,</span><br><span class="line">            data = <span class="keyword">self</span>.postdata)</span><br><span class="line">        result = <span class="keyword">self</span>.opener.open(request)</span><br><span class="line">        result = <span class="keyword">self</span>.opener.open(<span class="keyword">self</span>.gradeUrl)</span><br><span class="line">        <span class="comment">#打印登录内容</span></span><br><span class="line">        print result.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">sdu = SDU()</span><br><span class="line">sdu.getPage()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>上面的代码，我们最主要的是增加了</p>
                  <figure class="highlight oxygene">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">result</span> = <span class="keyword">self</span>.opener.open(<span class="keyword">self</span>.gradeUrl)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>这句代码，用原来的opener 访问一个本学期成绩的URL即可。运行结果如下 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220221909.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150220221909.jpg" alt="QQ截图20150220221909"></a> 恩，本学期成绩的页面已经被我们抓取下来了，接下来用正则表达式提取一下，然后计算学分即可</p>
                  <h2 id="4-抓取有效信息"><a href="#4-抓取有效信息" class="headerlink" title="4.抓取有效信息"></a>4.抓取有效信息</h2>
                  <p>接下来我们就把页面内容提取一下，最主要的便是学分以及分数了。 平均绩点 = ∑（每科学分*每科分数）/总学分 所以我们把每科的学分以及分数抓取下来就好了，对于有些课打了良好或者优秀等级的，我们不进行抓取。 我们可以发现每一科都是TR标签，然后是一系列的td标签</p>
                  <figure class="highlight xml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="tag">&lt;<span class="name">TR</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">td</span> <span class="attr">bgcolor</span>=<span class="string">"#EAE2F3"</span>&gt;</span><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span><span class="tag">&lt;<span class="name">INPUT</span> <span class="attr">TYPE</span>=<span class="string">"checkbox"</span> <span class="attr">NAME</span>=<span class="string">"p_pm"</span> <span class="attr">VALUE</span>=<span class="string">"013320131012015011294 面向对象技术"</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">td</span> <span class="attr">bgcolor</span>=<span class="string">"#EAE2F3"</span>&gt;</span><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span>0133201310<span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">td</span> <span class="attr">bgcolor</span>=<span class="string">"#EAE2F3"</span>&gt;</span><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span>面向对象技术<span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">td</span> <span class="attr">bgcolor</span>=<span class="string">"#EAE2F3"</span>&gt;</span><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span>1<span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">td</span> <span class="attr">bgcolor</span>=<span class="string">"#EAE2F3"</span>&gt;</span><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span>2.5<span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">td</span> <span class="attr">bgcolor</span>=<span class="string">"#EAE2F3"</span>&gt;</span><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span>20150112<span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">td</span> <span class="attr">bgcolor</span>=<span class="string">"#EAE2F3"</span>&gt;</span><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span>94<span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">td</span> <span class="attr">bgcolor</span>=<span class="string">"#EAE2F3"</span>&gt;</span><span class="tag">&lt;<span class="name">p</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span>必修<span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">TR</span>&gt;</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>我们用下面的正则表达式进行提取即可，部分代码如下</p>
                  <figure class="highlight vbnet">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">page = self.getPage()</span><br><span class="line">myItems = re.findall(<span class="comment">'<span class="doctag">&lt;TR&gt;</span>.*?<span class="doctag">&lt;p.*?&lt;p.*?&lt;p.*?&lt;p.*?&lt;p.*?&gt;</span>(.*?)<span class="doctag">&lt;/p&gt;</span>.*?<span class="doctag">&lt;p.*?&lt;p.*?&gt;</span>(.*?)<span class="doctag">&lt;/p&gt;</span>.*?<span class="doctag">&lt;/TR&gt;</span>',page,re.S) </span></span><br><span class="line"><span class="keyword">for</span> item <span class="keyword">in</span> myItems:</span><br><span class="line">   self.credit.append(item[<span class="number">0</span>].encode(<span class="comment">'gbk'))</span></span><br><span class="line">   self.grades.append(item[<span class="number">1</span>].encode(<span class="comment">'gbk'))</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>主要利用了findall方法，这个方法在此就不多介绍了，前面我们已经用过多次了。 得到的学分和分数我们都用列表list进行存储，所以用了 append 方法，每获取到一个信息就把它加进去。</p>
                  <h2 id="5-整理计算最后绩点"><a href="#5-整理计算最后绩点" class="headerlink" title="5.整理计算最后绩点"></a>5.整理计算最后绩点</h2>
                  <p>恩，像上面那样把学分绩点都保存到列表list中了，所以我们最后用一个公式来计算学分绩点就好了，最后整理后的代码如下：</p>
                  <figure class="highlight ruby">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-  </span></span><br><span class="line"></span><br><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line">import cookielib</span><br><span class="line">import re</span><br><span class="line">import string</span><br><span class="line"></span><br><span class="line"><span class="comment">#绩点运算</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SDU</span>:</span></span><br><span class="line">   </span><br><span class="line">   <span class="comment">#类的初始化</span></span><br><span class="line">   <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">      <span class="comment">#登录URL</span></span><br><span class="line">      <span class="keyword">self</span>.loginUrl = <span class="string">'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login'</span></span><br><span class="line">      <span class="comment">#成绩URL</span></span><br><span class="line">      <span class="keyword">self</span>.gradeUrl = <span class="string">'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bkscjcx.curscopre'</span></span><br><span class="line">      <span class="comment">#CookieJar对象</span></span><br><span class="line">      <span class="keyword">self</span>.cookies = cookielib.CookieJar()</span><br><span class="line">      <span class="comment">#表单数据</span></span><br><span class="line">      <span class="keyword">self</span>.postdata = urllib.urlencode(&#123;</span><br><span class="line">            <span class="string">'stuid'</span><span class="symbol">:<span class="string">'201200131012'</span></span>,</span><br><span class="line">            <span class="string">'pwd'</span><span class="symbol">:<span class="string">'xxxxx'</span></span></span><br><span class="line">         &#125;)</span><br><span class="line">      <span class="comment">#构建opener</span></span><br><span class="line">      <span class="keyword">self</span>.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(<span class="keyword">self</span>.cookies))</span><br><span class="line">      <span class="comment">#学分list</span></span><br><span class="line">      <span class="keyword">self</span>.credit = []</span><br><span class="line">      <span class="comment">#成绩list</span></span><br><span class="line">      <span class="keyword">self</span>.grades = []</span><br><span class="line">      </span><br><span class="line">   <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">      req  = urllib2.Request(</span><br><span class="line">            url = <span class="keyword">self</span>.loginUrl,</span><br><span class="line">            data = <span class="keyword">self</span>.postdata)</span><br><span class="line">      result = <span class="keyword">self</span>.opener.open(req)</span><br><span class="line">      result = <span class="keyword">self</span>.opener.open(<span class="keyword">self</span>.gradeUrl)</span><br><span class="line">      <span class="comment">#返回本学期成绩页面</span></span><br><span class="line">      <span class="keyword">return</span> result.read().decode(<span class="string">'gbk'</span>)</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">def</span> <span class="title">getGrades</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">      <span class="comment">#获得本学期成绩页面</span></span><br><span class="line">      page = <span class="keyword">self</span>.getPage()</span><br><span class="line">      <span class="comment">#正则匹配</span></span><br><span class="line">      myItems = re.findall(<span class="string">'&lt;TR&gt;.*?&lt;p.*?&lt;p.*?&lt;p.*?&lt;p.*?&lt;p.*?&gt;(.*?)&lt;/p&gt;.*?&lt;p.*?&lt;p.*?&gt;(.*?)&lt;/p&gt;.*?&lt;/TR&gt;'</span>,page,re.S) </span><br><span class="line">      <span class="keyword">for</span> item <span class="keyword">in</span> <span class="symbol">myItems:</span></span><br><span class="line">         <span class="keyword">self</span>.credit.append(item[<span class="number">0</span>].encode(<span class="string">'gbk'</span>))</span><br><span class="line">         <span class="keyword">self</span>.grades.append(item[<span class="number">1</span>].encode(<span class="string">'gbk'</span>))</span><br><span class="line">      <span class="keyword">self</span>.getGrade()</span><br><span class="line">      </span><br><span class="line">   <span class="function"><span class="keyword">def</span> <span class="title">getGrade</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">      <span class="comment">#计算总绩点</span></span><br><span class="line">      sum = <span class="number">0</span>.<span class="number">0</span></span><br><span class="line">      weight = <span class="number">0</span>.<span class="number">0</span></span><br><span class="line">      <span class="keyword">for</span> i <span class="keyword">in</span> range(len(<span class="keyword">self</span>.credit))<span class="symbol">:</span></span><br><span class="line">         <span class="keyword">if</span>(<span class="keyword">self</span>.grades[i].isdigit())<span class="symbol">:</span></span><br><span class="line">            sum += string.atof(<span class="keyword">self</span>.credit[i])*string.atof(<span class="keyword">self</span>.grades[i])</span><br><span class="line">            weight += string.atof(<span class="keyword">self</span>.credit[i])</span><br><span class="line">      </span><br><span class="line">      print u<span class="string">"本学期绩点为:"</span>,sum/weight</span><br><span class="line">      </span><br><span class="line">sdu = SDU()</span><br><span class="line">sdu.getGrades()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>好，最后就会打印输出本学期绩点是多少，小伙伴们最主要的了解上面的编程思路就好。 最主要的内容就是Cookie的使用，模拟登录的功能。 本文思路参考来源：<a href="http://blog.csdn.net/pleasecallmewhy/article/details/9305229" target="_blank" rel="noopener">汪海的爬虫</a> 希望小伙伴们加油，加深一下理解。</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-20 22:44:33" itemprop="dateCreated datePublished" datetime="2015-02-20T22:44:33+08:00">2015-02-20</time>
                </span>
                <span id="/997.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫实战七之计算大学本学期绩点" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>6k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>5 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/993.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/993.html" class="post-title-link" itemprop="url">Python爬虫实战二之爬取百度贴吧帖子</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>大家好，上次我们实验了爬取了糗事百科的段子，那么这次我们来尝试一下爬取百度贴吧的帖子。与上一篇不同的是，这次我们需要用到文件的相关操作。</p>
                  <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2>
                  <p>亲爱的们，教程比较旧了，百度贴吧页面可能改版，可能代码不好使，八成是正则表达式那儿匹配不到了，请更改一下正则，当然最主要的还是帮助大家理解思路。</p>
                  <p>2016/12/2</p>
                  <h2 id="本篇目标"><a href="#本篇目标" class="headerlink" title="本篇目标"></a>本篇目标</h2>
                  <p>1.对百度贴吧的任意帖子进行抓取 2.指定是否只抓取楼主发帖内容 3.将抓取到的内容分析并保存到文件</p>
                  <h2 id="1-URL格式的确定"><a href="#1-URL格式的确定" class="headerlink" title="1.URL格式的确定"></a>1.URL格式的确定</h2>
                  <p>首先，我们先观察一下百度贴吧的任意一个帖子。 比如：<a href="http://tieba.baidu.com/p/3138733512?see_lz=1&amp;pn=1" target="_blank" rel="noopener">http://tieba.baidu.com/p/3138733512?see_lz=1&amp;pn=1</a>，这是一个关于NBA50大的盘点，分析一下这个地址。</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">http:<span class="comment">//  代表资源传输使用http协议</span></span><br><span class="line">tieba.baidu.com 是百度的二级域名，指向百度贴吧的服务器。</span><br><span class="line">/p/<span class="number">3138733512</span> 是服务器某个资源，即这个帖子的地址定位符</span><br><span class="line">see_lz和pn是该URL的两个参数，分别代表了只看楼主和帖子页码，等于<span class="number">1</span>表示该条件为真</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>所以我们可以把URL分为两部分，一部分为基础部分，一部分为参数部分。 例如，上面的URL我们划分基础部分是 <a href="http://tieba.baidu.com/p/3138733512?see_lz=1&amp;pn=1" target="_blank" rel="noopener">http://tieba.baidu.com/p/3138733512</a>，参数部分是 <a href="http://tieba.baidu.com/p/3138733512?see_lz=1&amp;pn=1" target="_blank" rel="noopener">?see_lz=1&amp;pn=1</a></p>
                  <h2 id="2-页面的抓取"><a href="#2-页面的抓取" class="headerlink" title="2.页面的抓取"></a>2.页面的抓取</h2>
                  <p>熟悉了URL的格式，那就让我们用urllib2库来试着抓取页面内容吧。上一篇糗事百科我们最后改成了面向对象的编码方式，这次我们直接尝试一下，定义一个类名叫BDTB(百度贴吧)，一个初始化方法，一个获取页面的方法。 其中，有些帖子我们想指定给程序是否要只看楼主，所以我们把只看楼主的参数初始化放在类的初始化上，即init方法。另外，获取页面的方法我们需要知道一个参数就是帖子页码，所以这个参数的指定我们放在该方法中。 综上，我们初步构建出基础代码如下：</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"><span class="keyword">import</span> urllib</span><br><span class="line"><span class="keyword">import</span> urllib2</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"><span class="comment">#百度贴吧爬虫类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BDTB</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#初始化，传入基地址，是否只看楼主的参数</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,baseUrl,seeLZ)</span>:</span></span><br><span class="line">        self.baseURL = baseUrl</span><br><span class="line">        self.seeLZ = <span class="string">'?see_lz='</span>+str(seeLZ)</span><br><span class="line"></span><br><span class="line">    <span class="comment">#传入页码，获取该页帖子的代码</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(self,pageNum)</span>:</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            url = self.baseURL+ self.seeLZ + <span class="string">'&amp;pn='</span> + str(pageNum)</span><br><span class="line">            request = urllib2.Request(url)</span><br><span class="line">            response = urllib2.urlopen(request)</span><br><span class="line">            <span class="keyword">print</span> response.read()</span><br><span class="line">            <span class="keyword">return</span> response</span><br><span class="line">        <span class="keyword">except</span> urllib2.URLError, e:</span><br><span class="line">            <span class="keyword">if</span> hasattr(e,<span class="string">"reason"</span>):</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"连接百度贴吧失败,错误原因"</span>,e.reason</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">baseURL = <span class="string">'http://tieba.baidu.com/p/3138733512'</span></span><br><span class="line">bdtb = BDTB(baseURL,<span class="number">1</span>)</span><br><span class="line">bdtb.getPage(<span class="number">1</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行代码，我们可以看到屏幕上打印出了这个帖子第一页楼主发言的所有内容，形式为HTML代码。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150219162232.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150219162232.jpg" alt="20150219162232"></a></p>
                  <h2 id="3-提取相关信息"><a href="#3-提取相关信息" class="headerlink" title="3.提取相关信息"></a>3.提取相关信息</h2>
                  <h3 id="1）提取帖子标题"><a href="#1）提取帖子标题" class="headerlink" title="1）提取帖子标题"></a>1）提取帖子标题</h3>
                  <p>首先，让我们提取帖子的标题。 在浏览器中审查元素，或者按F12，查看页面源代码，我们找到标题所在的代码段，可以发现这个标题的HTML代码是</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;h1 <span class="attribute">class</span>=<span class="string">"core_title_txt  "</span> <span class="attribute">title</span>=<span class="string">"纯原创我心中的NBA2014-2015赛季现役50大"</span> <span class="attribute">style</span>=<span class="string">"width: 396px"</span>&gt;纯原创我心中的NBA2014-2015赛季现役50大&lt;/h1&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>所以我们想提取
                  <h1>标签中的内容，同时还要指定这个class确定唯一，因为h1标签实在太多啦。 正则表达式如下</p>
                    <figure class="highlight cpp">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">&lt;h1 <span class="class"><span class="keyword">class</span>="<span class="title">core_title_txt</span>.*?&gt;(.*?)&lt;/h1&gt;</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>所以，我们增加一个获取页面标题的方法</p>
                    <figure class="highlight routeros">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="comment">#获取帖子标题</span></span><br><span class="line">def getTitle(self):</span><br><span class="line">   <span class="built_in"> page </span>= self.getPage(1)</span><br><span class="line">    pattern = re.compile(<span class="string">'&lt;h1 class="core_title_txt.*?&gt;(.*?)&lt;/h1&gt;'</span>,re.S)</span><br><span class="line">    result = re.search(pattern,page)</span><br><span class="line">    <span class="keyword">if</span> result:</span><br><span class="line">        #<span class="builtin-name">print</span> result.group(1)  #测试输出</span><br><span class="line">        return result.group(1).strip()</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        return None</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <h3 id="2）提取帖子页数"><a href="#2）提取帖子页数" class="headerlink" title="2）提取帖子页数"></a>2）提取帖子页数</h3>
                    <p>同样地，帖子总页数我们也可以通过分析页面中的共?页来获取。所以我们的获取总页数的方法如下</p>
                    <figure class="highlight routeros">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="comment">#获取帖子一共有多少页</span></span><br><span class="line">def getPageNum(self):</span><br><span class="line">   <span class="built_in"> page </span>= self.getPage(1)</span><br><span class="line">    pattern = re.compile(<span class="string">'&lt;li class="l_reply_num.*?&lt;/span&gt;.*?&lt;span.*?&gt;(.*?)&lt;/span&gt;'</span>,re.S)</span><br><span class="line">    result = re.search(pattern,page)</span><br><span class="line">    <span class="keyword">if</span> result:</span><br><span class="line">        #<span class="builtin-name">print</span> result.group(1)  #测试输出</span><br><span class="line">        return result.group(1).strip()</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        return None</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <h3 id="3）提取正文内容"><a href="#3）提取正文内容" class="headerlink" title="3）提取正文内容"></a>3）提取正文内容</h3>
                    <p>审查元素，我们可以看到百度贴吧每一层楼的主要内容都在
                    <div id="post_content_xxxx"></div>标签里面，所以我们可以写如下的正则表达式</p>
                    <figure class="highlight applescript">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">&lt;<span class="keyword">div</span> <span class="built_in">id</span>=<span class="string">"post_content_.*?&gt;(.*?)&lt;/div&gt;</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>相应地，获取页面所有楼层数据的方法可以写成如下方法</p>
                    <figure class="highlight ruby">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="comment">#获取每一层楼的内容,传入页面内容</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getContent</span><span class="params">(<span class="keyword">self</span>,page)</span></span><span class="symbol">:</span></span><br><span class="line">    pattern = re.compile(<span class="string">'&lt;div id="post_content_.*?&gt;(.*?)&lt;/div&gt;'</span>,re.S)</span><br><span class="line">    items = re.findall(pattern,page)</span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> <span class="symbol">items:</span></span><br><span class="line">        print item</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>好，我们运行一下结果看一下 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150219235120.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150219235120-e1424361136128.jpg" alt="20150219235120"></a> 真是醉了，还有一大片换行符和图片符，好口怕！既然这样，我们就要对这些文本进行处理，把各种各样复杂的标签给它剔除掉，还原精华内容，把文本处理写成一个方法也可以，不过为了实现更好的代码架构和代码重用，我们可以考虑把标签等的处理写作一个类。 那我们就叫它Tool（工具类吧），里面定义了一个方法，叫replace，是替换各种标签的。在类中定义了几个正则表达式，主要利用了re.sub方法对文本进行匹配后然后替换。具体的思路已经写到注释中，大家可以看一下这个类</p>
                    <figure class="highlight vbnet">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">import re</span><br><span class="line"></span><br><span class="line"><span class="meta">#处理页面标签类</span></span><br><span class="line"><span class="keyword">class</span> Tool:</span><br><span class="line">    <span class="meta">#去除img标签,7位长空格</span></span><br><span class="line">    removeImg = re.compile(<span class="comment">'<span class="doctag">&lt;img.*?&gt;</span>| &#123;7&#125;|')</span></span><br><span class="line">    <span class="meta">#删除超链接标签</span></span><br><span class="line">    removeAddr = re.compile(<span class="comment">'<span class="doctag">&lt;a.*?&gt;</span>|<span class="doctag">&lt;/a&gt;</span>')</span></span><br><span class="line">    <span class="meta">#把换行的标签换为\n</span></span><br><span class="line">    replaceLine = re.compile(<span class="comment">'<span class="doctag">&lt;tr&gt;</span>|<span class="doctag">&lt;div&gt;</span>|<span class="doctag">&lt;/div&gt;</span>|<span class="doctag">&lt;/p&gt;</span>')</span></span><br><span class="line">    <span class="meta">#将表格制表&lt;td&gt;替换为\t</span></span><br><span class="line">    replaceTD= re.compile(<span class="comment">'<span class="doctag">&lt;td&gt;</span>')</span></span><br><span class="line">    <span class="meta">#把段落开头换为\n加空两格</span></span><br><span class="line">    replacePara = re.compile(<span class="comment">'<span class="doctag">&lt;p.*?&gt;</span>')</span></span><br><span class="line">    <span class="meta">#将换行符或双换行符替换为\n</span></span><br><span class="line">    replaceBR = re.compile(<span class="comment">'<span class="doctag">&lt;br&gt;</span><span class="doctag">&lt;br&gt;</span>|<span class="doctag">&lt;br&gt;</span>')</span></span><br><span class="line">    <span class="meta">#将其余标签剔除</span></span><br><span class="line">    removeExtraTag = re.compile(<span class="comment">'<span class="doctag">&lt;.*?&gt;</span>')</span></span><br><span class="line">    def replace(self,x):</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.removeImg,<span class="string">""</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.removeAddr,<span class="string">""</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.replaceLine,<span class="string">"\n"</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.replaceTD,<span class="string">"\t"</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.replacePara,<span class="string">"\n    "</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.replaceBR,<span class="string">"\n"</span>,x)</span><br><span class="line">        x = re.<span class="keyword">sub</span>(self.removeExtraTag,<span class="string">""</span>,x)</span><br><span class="line">        <span class="meta">#strip()将前后多余内容删除</span></span><br><span class="line">        <span class="keyword">return</span> x.strip()</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>在使用时，我们只需要初始化一下这个类，然后调用replace方法即可。 现在整体代码是如下这样子的，现在我的代码是写到这样子的</p>
                    <figure class="highlight ruby">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">__author_<span class="number">_</span> = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line">import re</span><br><span class="line"></span><br><span class="line"><span class="comment">#处理页面标签类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tool</span>:</span></span><br><span class="line">    <span class="comment">#去除img标签,7位长空格</span></span><br><span class="line">    removeImg = re.compile(<span class="string">'&lt;img.*?&gt;| &#123;7&#125;|'</span>)</span><br><span class="line">    <span class="comment">#删除超链接标签</span></span><br><span class="line">    removeAddr = re.compile(<span class="string">'&lt;a.*?&gt;|&lt;/a&gt;'</span>)</span><br><span class="line">    <span class="comment">#把换行的标签换为\n</span></span><br><span class="line">    replaceLine = re.compile(<span class="string">'&lt;tr&gt;|&lt;div&gt;|&lt;/div&gt;|&lt;/p&gt;'</span>)</span><br><span class="line">    <span class="comment">#将表格制表&lt;td&gt;替换为\t</span></span><br><span class="line">    replaceTD= re.compile(<span class="string">'&lt;td&gt;'</span>)</span><br><span class="line">    <span class="comment">#把段落开头换为\n加空两格</span></span><br><span class="line">    replacePara = re.compile(<span class="string">'&lt;p.*?&gt;'</span>)</span><br><span class="line">    <span class="comment">#将换行符或双换行符替换为\n</span></span><br><span class="line">    replaceBR = re.compile(<span class="string">'&lt;br&gt;&lt;br&gt;|&lt;br&gt;'</span>)</span><br><span class="line">    <span class="comment">#将其余标签剔除</span></span><br><span class="line">    removeExtraTag = re.compile(<span class="string">'&lt;.*?&gt;'</span>)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">replace</span><span class="params">(<span class="keyword">self</span>,x)</span></span><span class="symbol">:</span></span><br><span class="line">        x = re.sub(<span class="keyword">self</span>.removeImg,<span class="string">""</span>,x)</span><br><span class="line">        x = re.sub(<span class="keyword">self</span>.removeAddr,<span class="string">""</span>,x)</span><br><span class="line">        x = re.sub(<span class="keyword">self</span>.replaceLine,<span class="string">"\n"</span>,x)</span><br><span class="line">        x = re.sub(<span class="keyword">self</span>.replaceTD,<span class="string">"\t"</span>,x)</span><br><span class="line">        x = re.sub(<span class="keyword">self</span>.replacePara,<span class="string">"\n    "</span>,x)</span><br><span class="line">        x = re.sub(<span class="keyword">self</span>.replaceBR,<span class="string">"\n"</span>,x)</span><br><span class="line">        x = re.sub(<span class="keyword">self</span>.removeExtraTag,<span class="string">""</span>,x)</span><br><span class="line">        <span class="comment">#strip()将前后多余内容删除</span></span><br><span class="line">        <span class="keyword">return</span> x.strip()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#百度贴吧爬虫类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BDTB</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#初始化，传入基地址，是否只看楼主的参数</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(<span class="keyword">self</span>,baseUrl,seeLZ)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">self</span>.baseURL = baseUrl</span><br><span class="line">        <span class="keyword">self</span>.seeLZ = <span class="string">'?see_lz='</span>+str(seeLZ)</span><br><span class="line">        <span class="keyword">self</span>.tool = Tool()</span><br><span class="line">    <span class="comment">#传入页码，获取该页帖子的代码</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(<span class="keyword">self</span>,pageNum)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="symbol">try:</span></span><br><span class="line">            url = <span class="keyword">self</span>.baseURL+ <span class="keyword">self</span>.seeLZ + <span class="string">'&amp;pn='</span> + str(pageNum)</span><br><span class="line">            request = urllib2.Request(url)</span><br><span class="line">            response = urllib2.urlopen(request)</span><br><span class="line">            <span class="keyword">return</span> response.read().decode(<span class="string">'utf-8'</span>)</span><br><span class="line">        except urllib2.URLError, <span class="symbol">e:</span></span><br><span class="line">            <span class="keyword">if</span> hasattr(e,<span class="string">"reason"</span>)<span class="symbol">:</span></span><br><span class="line">                print u<span class="string">"连接百度贴吧失败,错误原因"</span>,e.reason</span><br><span class="line">                <span class="keyword">return</span> None</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取帖子标题</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getTitle</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        page = <span class="keyword">self</span>.getPage(<span class="number">1</span>)</span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;h1 class="core_title_txt.*?&gt;(.*?)&lt;/h1&gt;'</span>,re.S)</span><br><span class="line">        result = re.search(pattern,page)</span><br><span class="line">        <span class="keyword">if</span> <span class="symbol">result:</span></span><br><span class="line">            <span class="comment">#print result.group(1)  #测试输出</span></span><br><span class="line">            <span class="keyword">return</span> result.group(<span class="number">1</span>).strip()</span><br><span class="line">        <span class="symbol">else:</span></span><br><span class="line">            <span class="keyword">return</span> None</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取帖子一共有多少页</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPageNum</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        page = <span class="keyword">self</span>.getPage(<span class="number">1</span>)</span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;li class="l_reply_num.*?&lt;/span&gt;.*?&lt;span.*?&gt;(.*?)&lt;/span&gt;'</span>,re.S)</span><br><span class="line">        result = re.search(pattern,page)</span><br><span class="line">        <span class="keyword">if</span> <span class="symbol">result:</span></span><br><span class="line">            <span class="comment">#print result.group(1)  #测试输出</span></span><br><span class="line">            <span class="keyword">return</span> result.group(<span class="number">1</span>).strip()</span><br><span class="line">        <span class="symbol">else:</span></span><br><span class="line">            <span class="keyword">return</span> None</span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取每一层楼的内容,传入页面内容</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getContent</span><span class="params">(<span class="keyword">self</span>,page)</span></span><span class="symbol">:</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;div id="post_content_.*?&gt;(.*?)&lt;/div&gt;'</span>,re.S)</span><br><span class="line">        items = re.findall(pattern,page)</span><br><span class="line">        <span class="comment">#for item in items:</span></span><br><span class="line">        <span class="comment">#  print item</span></span><br><span class="line">        print <span class="keyword">self</span>.tool.replace(items[<span class="number">1</span>])</span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">baseURL = <span class="string">'http://tieba.baidu.com/p/3138733512'</span></span><br><span class="line">bdtb = BDTB(baseURL,<span class="number">1</span>)</span><br><span class="line">bdtb.getContent(bdtb.getPage(<span class="number">1</span>))</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>我们尝试一下，重新再看一下效果，这下经过处理之后应该就没问题了，是不是感觉好酸爽！ <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150220000103.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150220000103.jpg" alt="20150220000103"></a></p>
                    <h3 id="4）替换楼层"><a href="#4）替换楼层" class="headerlink" title="4）替换楼层"></a>4）替换楼层</h3>
                    <p>至于这个问题，我感觉直接提取楼层没什么必要呀，因为只看楼主的话，有些楼层的编号是间隔的，所以我们得到的楼层序号是不连续的，这样我们保存下来也没什么用。 所以可以尝试下面的方法：</p>
                    <blockquote>
                      <p>1.每打印输出一段楼层，写入一行横线来间隔，或者换行符也好。 2.试着重新编一个楼层，按照顺序，设置一个变量，每打印出一个结果变量加一，打印出这个变量当做楼层。</p>
                    </blockquote>
                    <p>这里我们尝试一下吧，看看效果怎样 把getContent方法修改如下</p>
                    <figure class="highlight python">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="comment">#获取每一层楼的内容,传入页面内容</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getContent</span><span class="params">(self,page)</span>:</span></span><br><span class="line">    pattern = re.compile(<span class="string">'&lt;div id="post_content_.*?&gt;(.*?)&lt;/div&gt;'</span>,re.S)</span><br><span class="line">    items = re.findall(pattern,page)</span><br><span class="line">    floor = <span class="number">1</span></span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> items:</span><br><span class="line">        <span class="keyword">print</span> floor,<span class="string">u"楼------------------------------------------------------------------------------------------------------------------------------------\n"</span></span><br><span class="line">        <span class="keyword">print</span> self.tool.replace(item)</span><br><span class="line">        floor += <span class="number">1</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>运行一下看看效果 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150220000947.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150220000947.jpg" alt="20150220000947"></a> 嘿嘿，效果还不错吧，感觉真酸爽！接下来我们完善一下，然后写入文件</p>
                    <h2 id="4-写入文件"><a href="#4-写入文件" class="headerlink" title="4.写入文件"></a>4.写入文件</h2>
                    <p>最后便是写入文件的过程，过程很简单，就几句话的代码而已，主要是利用了以下两句</p>
                    <blockquote>
                      <p>file = open(“tb.txt”,”w”) file.writelines(obj)</p>
                    </blockquote>
                    <p>这里不再赘述，稍后直接贴上完善之后的代码。</p>
                    <h2 id="5-完善代码"><a href="#5-完善代码" class="headerlink" title="5.完善代码"></a>5.完善代码</h2>
                    <p>现在我们对代码进行优化，重构，在一些地方添加必要的打印信息，整理如下</p>
                    <figure class="highlight python">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"><span class="keyword">import</span> urllib</span><br><span class="line"><span class="keyword">import</span> urllib2</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"><span class="comment">#处理页面标签类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tool</span>:</span></span><br><span class="line">    <span class="comment">#去除img标签,7位长空格</span></span><br><span class="line">    removeImg = re.compile(<span class="string">'&lt;img.*?&gt;| &#123;7&#125;|'</span>)</span><br><span class="line">    <span class="comment">#删除超链接标签</span></span><br><span class="line">    removeAddr = re.compile(<span class="string">'&lt;a.*?&gt;|&lt;/a&gt;'</span>)</span><br><span class="line">    <span class="comment">#把换行的标签换为\n</span></span><br><span class="line">    replaceLine = re.compile(<span class="string">'&lt;tr&gt;|&lt;div&gt;|&lt;/div&gt;|&lt;/p&gt;'</span>)</span><br><span class="line">    <span class="comment">#将表格制表&lt;td&gt;替换为\t</span></span><br><span class="line">    replaceTD= re.compile(<span class="string">'&lt;td&gt;'</span>)</span><br><span class="line">    <span class="comment">#把段落开头换为\n加空两格</span></span><br><span class="line">    replacePara = re.compile(<span class="string">'&lt;p.*?&gt;'</span>)</span><br><span class="line">    <span class="comment">#将换行符或双换行符替换为\n</span></span><br><span class="line">    replaceBR = re.compile(<span class="string">'&lt;br&gt;&lt;br&gt;|&lt;br&gt;'</span>)</span><br><span class="line">    <span class="comment">#将其余标签剔除</span></span><br><span class="line">    removeExtraTag = re.compile(<span class="string">'&lt;.*?&gt;'</span>)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">replace</span><span class="params">(self,x)</span>:</span></span><br><span class="line">        x = re.sub(self.removeImg,<span class="string">""</span>,x)</span><br><span class="line">        x = re.sub(self.removeAddr,<span class="string">""</span>,x)</span><br><span class="line">        x = re.sub(self.replaceLine,<span class="string">"\n"</span>,x)</span><br><span class="line">        x = re.sub(self.replaceTD,<span class="string">"\t"</span>,x)</span><br><span class="line">        x = re.sub(self.replacePara,<span class="string">"\n    "</span>,x)</span><br><span class="line">        x = re.sub(self.replaceBR,<span class="string">"\n"</span>,x)</span><br><span class="line">        x = re.sub(self.removeExtraTag,<span class="string">""</span>,x)</span><br><span class="line">        <span class="comment">#strip()将前后多余内容删除</span></span><br><span class="line">        <span class="keyword">return</span> x.strip()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#百度贴吧爬虫类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BDTB</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#初始化，传入基地址，是否只看楼主的参数</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self,baseUrl,seeLZ,floorTag)</span>:</span></span><br><span class="line">        <span class="comment">#base链接地址</span></span><br><span class="line">        self.baseURL = baseUrl</span><br><span class="line">        <span class="comment">#是否只看楼主</span></span><br><span class="line">        self.seeLZ = <span class="string">'?see_lz='</span>+str(seeLZ)</span><br><span class="line">        <span class="comment">#HTML标签剔除工具类对象</span></span><br><span class="line">        self.tool = Tool()</span><br><span class="line">        <span class="comment">#全局file变量，文件写入操作对象</span></span><br><span class="line">        self.file = <span class="literal">None</span></span><br><span class="line">        <span class="comment">#楼层标号，初始为1</span></span><br><span class="line">        self.floor = <span class="number">1</span></span><br><span class="line">        <span class="comment">#默认的标题，如果没有成功获取到标题的话则会用这个标题</span></span><br><span class="line">        self.defaultTitle = <span class="string">u"百度贴吧"</span></span><br><span class="line">        <span class="comment">#是否写入楼分隔符的标记</span></span><br><span class="line">        self.floorTag = floorTag</span><br><span class="line"></span><br><span class="line">    <span class="comment">#传入页码，获取该页帖子的代码</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(self,pageNum)</span>:</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="comment">#构建URL</span></span><br><span class="line">            url = self.baseURL+ self.seeLZ + <span class="string">'&amp;pn='</span> + str(pageNum)</span><br><span class="line">            request = urllib2.Request(url)</span><br><span class="line">            response = urllib2.urlopen(request)</span><br><span class="line">            <span class="comment">#返回UTF-8格式编码内容</span></span><br><span class="line">            <span class="keyword">return</span> response.read().decode(<span class="string">'utf-8'</span>)</span><br><span class="line">        <span class="comment">#无法连接，报错</span></span><br><span class="line">        <span class="keyword">except</span> urllib2.URLError, e:</span><br><span class="line">            <span class="keyword">if</span> hasattr(e,<span class="string">"reason"</span>):</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"连接百度贴吧失败,错误原因"</span>,e.reason</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取帖子标题</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getTitle</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        <span class="comment">#得到标题的正则表达式</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;h1 class="core_title_txt.*?&gt;(.*?)&lt;/h1&gt;'</span>,re.S)</span><br><span class="line">        result = re.search(pattern,page)</span><br><span class="line">        <span class="keyword">if</span> result:</span><br><span class="line">            <span class="comment">#如果存在，则返回标题</span></span><br><span class="line">            <span class="keyword">return</span> result.group(<span class="number">1</span>).strip()</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取帖子一共有多少页</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPageNum</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        <span class="comment">#获取帖子页数的正则表达式</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;li class="l_reply_num.*?&lt;/span&gt;.*?&lt;span.*?&gt;(.*?)&lt;/span&gt;'</span>,re.S)</span><br><span class="line">        result = re.search(pattern,page)</span><br><span class="line">        <span class="keyword">if</span> result:</span><br><span class="line">            <span class="keyword">return</span> result.group(<span class="number">1</span>).strip()</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#获取每一层楼的内容,传入页面内容</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getContent</span><span class="params">(self,page)</span>:</span></span><br><span class="line">        <span class="comment">#匹配所有楼层的内容</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;div id="post_content_.*?&gt;(.*?)&lt;/div&gt;'</span>,re.S)</span><br><span class="line">        items = re.findall(pattern,page)</span><br><span class="line">        contents = []</span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> items:</span><br><span class="line">            <span class="comment">#将文本进行去除标签处理，同时在前后加入换行符</span></span><br><span class="line">            content = <span class="string">"\n"</span>+self.tool.replace(item)+<span class="string">"\n"</span></span><br><span class="line">            contents.append(content.encode(<span class="string">'utf-8'</span>))</span><br><span class="line">        <span class="keyword">return</span> contents</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">setFileTitle</span><span class="params">(self,title)</span>:</span></span><br><span class="line">        <span class="comment">#如果标题不是为None，即成功获取到标题</span></span><br><span class="line">        <span class="keyword">if</span> title <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">            self.file = open(title + <span class="string">".txt"</span>,<span class="string">"w+"</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.file = open(self.defaultTitle + <span class="string">".txt"</span>,<span class="string">"w+"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">writeData</span><span class="params">(self,contents)</span>:</span></span><br><span class="line">        <span class="comment">#向文件写入每一楼的信息</span></span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> contents:</span><br><span class="line">            <span class="keyword">if</span> self.floorTag == <span class="string">'1'</span>:</span><br><span class="line">                <span class="comment">#楼之间的分隔符</span></span><br><span class="line">                floorLine = <span class="string">"\n"</span> + str(self.floor) + <span class="string">u"-----------------------------------------------------------------------------------------\n"</span></span><br><span class="line">                self.file.write(floorLine)</span><br><span class="line">            self.file.write(item)</span><br><span class="line">            self.floor += <span class="number">1</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">start</span><span class="params">(self)</span>:</span></span><br><span class="line">        indexPage = self.getPage(<span class="number">1</span>)</span><br><span class="line">        pageNum = self.getPageNum(indexPage)</span><br><span class="line">        title = self.getTitle(indexPage)</span><br><span class="line">        self.setFileTitle(title)</span><br><span class="line">        <span class="keyword">if</span> pageNum == <span class="literal">None</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">"URL已失效，请重试"</span></span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">"该帖子共有"</span> + str(pageNum) + <span class="string">"页"</span></span><br><span class="line">            <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>,int(pageNum)+<span class="number">1</span>):</span><br><span class="line">                <span class="keyword">print</span> <span class="string">"正在写入第"</span> + str(i) + <span class="string">"页数据"</span></span><br><span class="line">                page = self.getPage(i)</span><br><span class="line">                contents = self.getContent(page)</span><br><span class="line">                self.writeData(contents)</span><br><span class="line">        <span class="comment">#出现写入异常</span></span><br><span class="line">        <span class="keyword">except</span> IOError,e:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">"写入异常，原因"</span> + e.message</span><br><span class="line">        <span class="keyword">finally</span>:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">"写入任务完成"</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">print</span> <span class="string">u"请输入帖子代号"</span></span><br><span class="line">baseURL = <span class="string">'http://tieba.baidu.com/p/'</span> + str(raw_input(<span class="string">u'http://tieba.baidu.com/p/'</span>))</span><br><span class="line">seeLZ = raw_input(<span class="string">"是否只获取楼主发言，是输入1，否输入0\n"</span>)</span><br><span class="line">floorTag = raw_input(<span class="string">"是否写入楼层信息，是输入1，否输入0\n"</span>)</span><br><span class="line">bdtb = BDTB(baseURL,seeLZ,floorTag)</span><br><span class="line">bdtb.start()</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>现在程序演示如下 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150220012351.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150220012351.jpg" alt="20150220012351"></a> 完成之后，可以查看一下当前目录下多了一个以该帖子命名的txt文件，内容便是帖子的所有数据。 抓贴吧，就是这么简单和任性！</p>
                    </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-17 01:09:52" itemprop="dateCreated datePublished" datetime="2015-02-17T01:09:52+08:00">2015-02-17</time>
                </span>
                <span id="/993.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫实战二之爬取百度贴吧帖子" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>10k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>9 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/990.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/990.html" class="post-title-link" itemprop="url">Python爬虫实战一之爬取糗事百科段子</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>大家好，前面入门已经说了那么多基础知识了，下面我们做几个实战项目来挑战一下吧。那么这次为大家带来，Python爬取糗事百科的小段子的例子。 首先，糗事百科大家都听说过吧？糗友们发的搞笑的段子一抓一大把，这次我们尝试一下用爬虫把他们抓取下来。</p>
                  <h2 id="友情提示"><a href="#友情提示" class="headerlink" title="友情提示"></a>友情提示</h2>
                  <blockquote>
                    <p>糗事百科在前一段时间进行了改版，导致之前的代码没法用了，会导致无法输出和CPU占用过高的情况，是因为正则表达式没有匹配到的缘故。 现在，博主已经对程序进行了重新修改，代码亲测可用，包括截图和说明，之前一直在忙所以没有及时更新，望大家海涵！ 更新时间：2015/8/2</p>
                    <p>糗事百科又又又又改版了，博主已经没心再去一次次匹配它了，如果大家遇到长时间运行不出结果也不报错的情况，请大家参考最新的评论，热心小伙伴提供的正则来修改下吧～ 更新时间：2016/3/27</p>
                  </blockquote>
                  <h2 id="本篇目标"><a href="#本篇目标" class="headerlink" title="本篇目标"></a>本篇目标</h2>
                  <blockquote>
                    <p>1.抓取糗事百科热门段子 2.过滤带有图片的段子 3.实现每按一次回车显示一个段子的发布时间，发布人，段子内容，点赞数。</p>
                  </blockquote>
                  <p>糗事百科是不需要登录的，所以也没必要用到Cookie，另外糗事百科有的段子是附图的，我们把图抓下来图片不便于显示，那么我们就尝试过滤掉有图的段子吧。 好，现在我们尝试抓取一下糗事百科的热门段子吧，每按下一次回车我们显示一个段子。</p>
                  <h2 id="1-确定URL并抓取页面代码"><a href="#1-确定URL并抓取页面代码" class="headerlink" title="1.确定URL并抓取页面代码"></a>1.确定URL并抓取页面代码</h2>
                  <p>首先我们确定好页面的URL是 <a href="http://www.qiushibaike.com/hot/page/1，其中最后一个数字1代表页数，我们可以传入不同的值来获得某一页的段子内容。" target="_blank" rel="noopener">http://www.qiushibaike.com/hot/page/1，其中最后一个数字1代表页数，我们可以传入不同的值来获得某一页的段子内容。</a> 我们初步构建如下的代码来打印页面代码内容试试看，先构造最基本的页面抓取方式，看看会不会成功</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">page = 1</span><br><span class="line">url = <span class="string">'http://www.qiushibaike.com/hot/page/'</span> + str(page)</span><br><span class="line">try:</span><br><span class="line">    request = urllib2.Request(url)</span><br><span class="line">    response = urllib2.urlopen(request)</span><br><span class="line">    <span class="builtin-name">print</span> response.read()</span><br><span class="line">except urllib2.URLError, e:</span><br><span class="line">    <span class="keyword">if</span> hasattr(e,<span class="string">"code"</span>):</span><br><span class="line">        <span class="builtin-name">print</span> e.code</span><br><span class="line">    <span class="keyword">if</span> hasattr(e,<span class="string">"reason"</span>):</span><br><span class="line">        <span class="builtin-name">print</span> e.reason</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行程序，哦不，它竟然报错了，真是时运不济，命途多舛啊</p>
                  <figure class="highlight pgsql">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="type">line</span> <span class="number">373</span>, <span class="keyword">in</span> _read_status</span><br><span class="line"> <span class="keyword">raise</span> BadStatusLine(<span class="type">line</span>)</span><br><span class="line">httplib.BadStatusLine: <span class="string">''</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>好吧，应该是headers验证的问题，我们加上一个headers验证试试看吧，将代码修改如下</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line"></span><br><span class="line">page = 1</span><br><span class="line">url = <span class="string">'http://www.qiushibaike.com/hot/page/'</span> + str(page)</span><br><span class="line">user_agent = <span class="string">'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'</span></span><br><span class="line">headers = &#123; <span class="string">'User-Agent'</span> : user_agent &#125;</span><br><span class="line">try:</span><br><span class="line">    request = urllib2.Request(url,headers = headers)</span><br><span class="line">    response = urllib2.urlopen(request)</span><br><span class="line">    <span class="builtin-name">print</span> response.read()</span><br><span class="line">except urllib2.URLError, e:</span><br><span class="line">    <span class="keyword">if</span> hasattr(e,<span class="string">"code"</span>):</span><br><span class="line">        <span class="builtin-name">print</span> e.code</span><br><span class="line">    <span class="keyword">if</span> hasattr(e,<span class="string">"reason"</span>):</span><br><span class="line">        <span class="builtin-name">print</span> e.reason</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>嘿嘿，这次运行终于正常了，打印出了第一页的HTML代码，大家可以运行下代码试试看。在这里运行结果太长就不贴了。</p>
                  <h2 id="2-提取某一页的所有段子"><a href="#2-提取某一页的所有段子" class="headerlink" title="2.提取某一页的所有段子"></a>2.提取某一页的所有段子</h2>
                  <p>好，获取了HTML代码之后，我们开始分析怎样获取某一页的所有段子。 首先我们审查元素看一下，按浏览器的F12，截图如下 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150802154147.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150802154147.jpg" alt="20150802154147"></a> 我们可以看到，每一个段子都是
                  <div class="article block untagged mb15" id="...">...</div>包裹的内容。 现在我们想获取发布人，发布日期，段子内容，以及点赞的个数。不过另外注意的是，段子有些是带图片的，如果我们想在控制台显示图片是不现实的，所以我们直接把带有图片的段子给它剔除掉，只保存仅含文本的段子。 所以我们加入如下正则表达式来匹配一下，用到的方法是 re.findall 是找寻所有匹配的内容。方法的用法详情可以看前面说的正则表达式的介绍。 好，我们的正则表达式匹配语句书写如下，在原来的基础上追加如下代码</p>
                  <figure class="highlight django">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="xml">content = response.read().decode('utf-8')</span></span><br><span class="line"><span class="xml">pattern = re.compile('<span class="tag">&lt;<span class="name">div.*?author"</span>&gt;</span>.*?<span class="tag">&lt;<span class="name">a.*?</span>&lt;<span class="attr">img.</span>*?&gt;</span>(.*?)<span class="tag">&lt;/<span class="name">a</span>&gt;</span>.*?<span class="tag">&lt;<span class="name">div.*?'+</span></span></span></span><br><span class="line"><span class="xml">                         'content"&gt;(.*?)<span class="comment">&lt;!--(.*?)--&gt;</span>.*?<span class="tag">&lt;/<span class="name">div</span>&gt;</span>(.*?)<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"stats.*?class="</span><span class="attr">number</span>"&gt;</span>(.*?)<span class="tag">&lt;/<span class="name">i</span>&gt;</span>',re.S)</span></span><br><span class="line"><span class="xml">items = re.findall(pattern,content)</span></span><br><span class="line"><span class="xml">for item in items:</span></span><br><span class="line"><span class="xml">    print item[0],item[1],item[2],item[3],item[4]</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>现在正则表达式在这里稍作说明 1）.<em>? 是一个固定的搭配，.和</em>代表可以匹配任意无限多个字符，加上？表示使用非贪婪模式进行匹配，也就是我们会尽可能短地做匹配，以后我们还会大量用到 .<em>? 的搭配。 2）(.</em>?)代表一个分组，在这个正则表达式中我们匹配了五个分组，在后面的遍历item中，item[0]就代表第一个(.<em>?)所指代的内容，item[1]就代表第二个(.</em>?)所指代的内容，以此类推。 3）re.S 标志代表在匹配时为点任意匹配模式，点 . 也可以代表换行符。 这样我们就获取了发布人，发布时间，发布内容，附加图片以及点赞数。 在这里注意一下，我们要获取的内容如果是带有图片，直接输出出来比较繁琐，所以这里我们只获取不带图片的段子就好了。 所以，在这里我们就需要对带图片的段子进行过滤。 我们可以发现，带有图片的段子会带有类似下面的代码，而不带图片的则没有，所以，我们的正则表达式的item[3]就是获取了下面的内容，如果不带图片，item[3]获取的内容便是空。</p>
                  <figure class="highlight javascript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">&lt;div <span class="class"><span class="keyword">class</span></span>=<span class="string">"thumb"</span>&gt;</span><br><span class="line"></span><br><span class="line">&lt;a href=<span class="string">"/article/112061287?list=hot&amp;amp;s=4794990"</span> target=<span class="string">"_blank"</span>&gt;</span><br><span class="line">&lt;img src=<span class="string">"http://pic.qiushibaike.com/system/pictures/11206/112061287/medium/app112061287.jpg"</span> alt=<span class="string">"但他们依然乐观"</span>&gt;</span><br><span class="line">&lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">&lt;/</span>div&gt;</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>所以我们只需要判断item[3]中是否含有img标签就可以了。 好，我们再把上述代码中的for循环改为下面的样子</p>
                  <figure class="highlight livecodeserver">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">for</span> <span class="keyword">item</span> <span class="keyword">in</span> <span class="keyword">items</span>:</span><br><span class="line">        haveImg = re.search(<span class="string">"img"</span>,<span class="keyword">item</span>[<span class="number">3</span>])</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> haveImg:</span><br><span class="line">            print <span class="keyword">item</span>[<span class="number">0</span>],<span class="keyword">item</span>[<span class="number">1</span>],<span class="keyword">item</span>[<span class="number">2</span>],<span class="keyword">item</span>[<span class="number">4</span>]</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>现在，整体的代码如下</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line">import re</span><br><span class="line"></span><br><span class="line">page = 1</span><br><span class="line">url = <span class="string">'http://www.qiushibaike.com/hot/page/'</span> + str(page)</span><br><span class="line">user_agent = <span class="string">'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'</span></span><br><span class="line">headers = &#123; <span class="string">'User-Agent'</span> : user_agent &#125;</span><br><span class="line">try:</span><br><span class="line">    request = urllib2.Request(url,headers = headers)</span><br><span class="line">    response = urllib2.urlopen(request)</span><br><span class="line">    content = response.read().decode(<span class="string">'utf-8'</span>)</span><br><span class="line">    pattern = re.compile(<span class="string">'&lt;div.*?author"&gt;.*?&lt;a.*?&lt;img.*?&gt;(.*?)&lt;/a&gt;.*?&lt;div.*?'</span>+</span><br><span class="line">                         <span class="string">'content"&gt;(.*?)&lt;!--(.*?)--&gt;.*?&lt;/div&gt;(.*?)&lt;div class="stats.*?class="number"&gt;(.*?)&lt;/i&gt;'</span>,re.S)</span><br><span class="line">    items = re.findall(pattern,content)</span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> items:</span><br><span class="line">        haveImg = re.search(<span class="string">"img"</span>,item[3])</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> haveImg:</span><br><span class="line">            <span class="builtin-name">print</span> item[0],item[1],item[2],item[4]</span><br><span class="line">except urllib2.URLError, e:</span><br><span class="line">    <span class="keyword">if</span> hasattr(e,<span class="string">"code"</span>):</span><br><span class="line">        <span class="builtin-name">print</span> e.code</span><br><span class="line">    <span class="keyword">if</span> hasattr(e,<span class="string">"reason"</span>):</span><br><span class="line">        <span class="builtin-name">print</span> e.reason</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行一下看下效果 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150802154832.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20150802154832.jpg" alt="20150802154832"></a> 恩，带有图片的段子已经被剔除啦。是不是很开森？</p>
                  <h2 id="3-完善交互，设计面向对象模式"><a href="#3-完善交互，设计面向对象模式" class="headerlink" title="3.完善交互，设计面向对象模式"></a>3.完善交互，设计面向对象模式</h2>
                  <p>好啦，现在最核心的部分我们已经完成啦，剩下的就是修一下边边角角的东西，我们想达到的目的是： 按下回车，读取一个段子，显示出段子的发布人，发布日期，内容以及点赞个数。 另外我们需要设计面向对象模式，引入类和方法，将代码做一下优化和封装，最后，我们的代码如下所示</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding:utf-8 -*-</span></span><br><span class="line"><span class="keyword">import</span> urllib</span><br><span class="line"><span class="keyword">import</span> urllib2</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">import</span> thread</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="comment">#糗事百科爬虫类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">QSBK</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">#初始化方法，定义一些变量</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.pageIndex = <span class="number">1</span></span><br><span class="line">        self.user_agent = <span class="string">'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'</span></span><br><span class="line">        <span class="comment">#初始化headers</span></span><br><span class="line">        self.headers = &#123; <span class="string">'User-Agent'</span> : self.user_agent &#125;</span><br><span class="line">        <span class="comment">#存放段子的变量，每一个元素是每一页的段子们</span></span><br><span class="line">        self.stories = []</span><br><span class="line">        <span class="comment">#存放程序是否继续运行的变量</span></span><br><span class="line">        self.enable = <span class="literal">False</span></span><br><span class="line">    <span class="comment">#传入某一页的索引获得页面代码</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPage</span><span class="params">(self,pageIndex)</span>:</span></span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            url = <span class="string">'http://www.qiushibaike.com/hot/page/'</span> + str(pageIndex)</span><br><span class="line">            <span class="comment">#构建请求的request</span></span><br><span class="line">            request = urllib2.Request(url,headers = self.headers)</span><br><span class="line">            <span class="comment">#利用urlopen获取页面代码</span></span><br><span class="line">            response = urllib2.urlopen(request)</span><br><span class="line">            <span class="comment">#将页面转化为UTF-8编码</span></span><br><span class="line">            pageCode = response.read().decode(<span class="string">'utf-8'</span>)</span><br><span class="line">            <span class="keyword">return</span> pageCode</span><br><span class="line"></span><br><span class="line">        <span class="keyword">except</span> urllib2.URLError, e:</span><br><span class="line">            <span class="keyword">if</span> hasattr(e,<span class="string">"reason"</span>):</span><br><span class="line">                <span class="keyword">print</span> <span class="string">u"连接糗事百科失败,错误原因"</span>,e.reason</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">#传入某一页代码，返回本页不带图片的段子列表</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getPageItems</span><span class="params">(self,pageIndex)</span>:</span></span><br><span class="line">        pageCode = self.getPage(pageIndex)</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> pageCode:</span><br><span class="line">            <span class="keyword">print</span> <span class="string">"页面加载失败...."</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">None</span></span><br><span class="line">        pattern = re.compile(<span class="string">'&lt;div.*?author"&gt;.*?&lt;a.*?&lt;img.*?&gt;(.*?)&lt;/a&gt;.*?&lt;div.*?'</span>+</span><br><span class="line">                         <span class="string">'content"&gt;(.*?)&lt;!--(.*?)--&gt;.*?&lt;/div&gt;(.*?)&lt;div class="stats.*?class="number"&gt;(.*?)&lt;/i&gt;'</span>,re.S)</span><br><span class="line">        items = re.findall(pattern,pageCode)</span><br><span class="line">        <span class="comment">#用来存储每页的段子们</span></span><br><span class="line">        pageStories = []</span><br><span class="line">        <span class="comment">#遍历正则表达式匹配的信息</span></span><br><span class="line">        <span class="keyword">for</span> item <span class="keyword">in</span> items:</span><br><span class="line">            <span class="comment">#是否含有图片</span></span><br><span class="line">            haveImg = re.search(<span class="string">"img"</span>,item[<span class="number">3</span>])</span><br><span class="line">            <span class="comment">#如果不含有图片，把它加入list中</span></span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> haveImg:</span><br><span class="line">                replaceBR = re.compile(<span class="string">'&lt;br/&gt;'</span>)</span><br><span class="line">                text = re.sub(replaceBR,<span class="string">"\n"</span>,item[<span class="number">1</span>])</span><br><span class="line">                <span class="comment">#item[0]是一个段子的发布者，item[1]是内容，item[2]是发布时间,item[4]是点赞数</span></span><br><span class="line">                pageStories.append([item[<span class="number">0</span>].strip(),text.strip(),item[<span class="number">2</span>].strip(),item[<span class="number">4</span>].strip()])</span><br><span class="line">        <span class="keyword">return</span> pageStories</span><br><span class="line"></span><br><span class="line">    <span class="comment">#加载并提取页面的内容，加入到列表中</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">loadPage</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="comment">#如果当前未看的页数少于2页，则加载新一页</span></span><br><span class="line">        <span class="keyword">if</span> self.enable == <span class="literal">True</span>:</span><br><span class="line">            <span class="keyword">if</span> len(self.stories) &lt; <span class="number">2</span>:</span><br><span class="line">                <span class="comment">#获取新一页</span></span><br><span class="line">                pageStories = self.getPageItems(self.pageIndex)</span><br><span class="line">                <span class="comment">#将该页的段子存放到全局list中</span></span><br><span class="line">                <span class="keyword">if</span> pageStories:</span><br><span class="line">                    self.stories.append(pageStories)</span><br><span class="line">                    <span class="comment">#获取完之后页码索引加一，表示下次读取下一页</span></span><br><span class="line">                    self.pageIndex += <span class="number">1</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">#调用该方法，每次敲回车打印输出一个段子</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getOneStory</span><span class="params">(self,pageStories,page)</span>:</span></span><br><span class="line">        <span class="comment">#遍历一页的段子</span></span><br><span class="line">        <span class="keyword">for</span> story <span class="keyword">in</span> pageStories:</span><br><span class="line">            <span class="comment">#等待用户输入</span></span><br><span class="line">            input = raw_input()</span><br><span class="line">            <span class="comment">#每当输入回车一次，判断一下是否要加载新页面</span></span><br><span class="line">            self.loadPage()</span><br><span class="line">            <span class="comment">#如果输入Q则程序结束</span></span><br><span class="line">            <span class="keyword">if</span> input == <span class="string">"Q"</span>:</span><br><span class="line">                self.enable = <span class="literal">False</span></span><br><span class="line">                <span class="keyword">return</span></span><br><span class="line">            <span class="keyword">print</span> <span class="string">u"第%d页\t发布人:%s\t发布时间:%s\t赞:%s\n%s"</span> %(page,story[<span class="number">0</span>],story[<span class="number">2</span>],story[<span class="number">3</span>],story[<span class="number">1</span>])</span><br><span class="line">    </span><br><span class="line">    <span class="comment">#开始方法</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">start</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">print</span> <span class="string">u"正在读取糗事百科,按回车查看新段子，Q退出"</span></span><br><span class="line">        <span class="comment">#使变量为True，程序可以正常运行</span></span><br><span class="line">        self.enable = <span class="literal">True</span></span><br><span class="line">        <span class="comment">#先加载一页内容</span></span><br><span class="line">        self.loadPage()</span><br><span class="line">        <span class="comment">#局部变量，控制当前读到了第几页</span></span><br><span class="line">        nowPage = <span class="number">0</span></span><br><span class="line">        <span class="keyword">while</span> self.enable:</span><br><span class="line">            <span class="keyword">if</span> len(self.stories)&gt;<span class="number">0</span>:</span><br><span class="line">                <span class="comment">#从全局list中获取一页的段子</span></span><br><span class="line">                pageStories = self.stories[<span class="number">0</span>]</span><br><span class="line">                <span class="comment">#当前读到的页数加一</span></span><br><span class="line">                nowPage += <span class="number">1</span></span><br><span class="line">                <span class="comment">#将全局list中第一个元素删除，因为已经取出</span></span><br><span class="line">                <span class="keyword">del</span> self.stories[<span class="number">0</span>]</span><br><span class="line">                <span class="comment">#输出该页的段子</span></span><br><span class="line">                self.getOneStory(pageStories,nowPage)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">spider = QSBK()</span><br><span class="line">spider.start()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>好啦，大家来测试一下吧，点一下回车会输出一个段子，包括发布人，发布时间，段子内容以及点赞数，是不是感觉爽爆了！ 我们第一个爬虫实战项目介绍到这里，欢迎大家继续关注，小伙伴们加油！</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-17 01:07:54" itemprop="dateCreated datePublished" datetime="2015-02-17T01:07:54+08:00">2015-02-17</time>
                </span>
                <span id="/990.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫实战一之爬取糗事百科段子" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>6.7k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>6 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/912.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/912.html" class="post-title-link" itemprop="url">Python爬虫进阶三之Scrapy框架安装配置</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>初级的爬虫我们利用urllib和urllib2库以及正则表达式就可以完成了，不过还有更加强大的工具，爬虫框架Scrapy，这安装过程也是煞费苦心哪，在此整理如下。</p>
                  <h2 id="Windows-平台："><a href="#Windows-平台：" class="headerlink" title="Windows 平台："></a>Windows 平台：</h2>
                  <p>我的系统是 Win7，首先，你要有Python，我用的是2.7.7版本，Python3相仿，只是一些源文件不同。 官网文档：<a href="http://doc.scrapy.org/en/latest/intro/install.html" target="_blank" rel="noopener">http://doc.scrapy.org/en/latest/intro/install.html</a>，最权威哒，下面是我的亲身体验过程。 1.安装Python 安装过程我就不多说啦，我的电脑中已经安装了 Python 2.7.7 版本啦，安装完之后记得配置环境变量，比如我的安装在D盘，D:\python2.7.7，就把以下两个路径添加到Path变量中</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">D:\python2<span class="number">.7</span><span class="number">.7</span>;D:\python2<span class="number">.7</span><span class="number">.7</span>\Scripts</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>配置好了之后，在命令行中输入 python —version，如果没有提示错误，则安装成功 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211171953.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211171953.jpg" alt="QQ截图20150211171953"></a> 2.安装pywin32 在windows下，必须安装pywin32，安装地址：<a href="http://sourceforge.net/projects/pywin32/" target="_blank" rel="noopener">http://sourceforge.net/projects/pywin32/</a> 下载对应版本的pywin32，直接双击安装即可，安装完毕之后验证： <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211171713.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211171713.jpg" alt="QQ截图20150211171713"></a> 在python命令行下输入 import win32com 如果没有提示错误，则证明安装成功 3.安装pip pip是用来安装其他必要包的工具，首先下载 <a href="https://bootstrap.pypa.io/get-pip.py" target="_blank" rel="noopener">get-pip.py</a> 下载好之后，选中该文件所在路径，执行下面的命令</p>
                  <figure class="highlight vim">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">python</span> <span class="built_in">get</span>-pip.<span class="keyword">py</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>执行命令后便会安装好pip，并且同时，它帮你安装了<a href="https://pypi.python.org/pypi/setuptools" target="_blank" rel="noopener">setuptools</a> 安装完了之后在命令行中执行</p>
                  <figure class="highlight ada">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">pip <span class="comment">--version</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>如果提示如下，说明就安装成功了，如果提示不是内部或外部命令，那么就检查一下环境变量有没有配置好吧，有两个路径。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211171001.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211171001.jpg" alt="QQ截图20150211171001"></a> 4.安装pyOPENSSL 在Windows下，是没有预装pyOPENSSL的，而在Linux下是已经安装好的。 安装地址：<a href="https://launchpad.net/pyopenssl" target="_blank" rel="noopener">https://launchpad.net/pyopenssl</a> 5.安装 lxml lxml的详细介绍 <a href="http://lxml.de/" target="_blank" rel="noopener">点我</a> ，是一种使用 Python 编写的库，可以迅速、灵活地处理 XML 直接执行如下命令</p>
                  <figure class="highlight cmake">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">pip <span class="keyword">install</span> lxml</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>就可完成安装，如果提示 Microsoft Visual C++库没安装，则 <a href="http://www.microsoft.com/en-us/download/details.aspx?id=44266" target="_blank" rel="noopener">点我</a> 下载支持的库。 6.安装Scrapy 最后就是激动人心的时刻啦，上面的铺垫做好了，我们终于可以享受到胜利的果实啦！ 执行如下命令</p>
                  <figure class="highlight cmake">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">pip <span class="keyword">install</span> Scrapy</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p><a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211172637.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211172637.jpg" alt="QQ截图20150211172637"></a> pip 会另外下载其他依赖的包，这些就不要我们手动安装啦，等待一会，大功告成！ 7.验证安装 输入 Scrapy 如果提示如下命令，就证明安装成功啦，如果失败了，请检查上述步骤有何疏漏。 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211172456.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150211172456-e1423673746697.jpg" alt="QQ截图20150211172456"></a></p>
                  <h2 id="Linux-Ubuntu-平台："><a href="#Linux-Ubuntu-平台：" class="headerlink" title="Linux Ubuntu 平台："></a>Linux Ubuntu 平台：</h2>
                  <p>Linux 下安装非常简单，只需要执行几条命令几个 1.安装Python</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">sudo apt-<span class="keyword">get</span> install python2<span class="number">.7</span> python2<span class="number">.7</span>-dev</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>2.安装 pip 首先下载 <a href="https://bootstrap.pypa.io/get-pip.py" target="_blank" rel="noopener">get-pip.py</a> 下载好之后，选中该文件所在路径，执行下面的命令</p>
                  <figure class="highlight vim">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">sudo <span class="keyword">python</span> <span class="built_in">get</span>-pip.<span class="keyword">py</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>3.直接安装 Scrapy 由于 Linux下已经预装了 lxml 和 OPENSSL 如果想验证 lxml ，可以分别输入</p>
                  <figure class="highlight cmake">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">sudo pip <span class="keyword">install</span> lxml</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>出现下面的提示这证明已经安装成功</p>
                  <figure class="highlight crystal">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/<span class="class"><span class="keyword">lib</span>/<span class="title">python2</span>.7/<span class="title">dist</span>-<span class="title">packages</span></span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>如果想验证 openssl，则直接输入openssl 即可，如果跳转到 OPENSSL 命令行，则安装成功。 接下来直接安装 Scrapy 即可</p>
                  <figure class="highlight cmake">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">sudo pip <span class="keyword">install</span> Scrapy</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>安装完毕之后，输入 scrapy 注意，这里linux下不要输入Scrapy，linux依然严格区分大小写的，感谢kamen童鞋提醒。 如果出现如下提示，这证明安装成功</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">Usage:</span><br><span class="line"> scrapy &lt;command&gt; [options] [args]</span><br><span class="line"></span><br><span class="line">Available commands:</span><br><span class="line"> bench <span class="builtin-name">Run</span> quick benchmark test</span><br><span class="line"> fetch Fetch a URL using the Scrapy downloader</span><br><span class="line"> runspider <span class="builtin-name">Run</span> a self-contained spider (without creating a project)</span><br><span class="line"><span class="built_in"> settings </span><span class="builtin-name">Get</span><span class="built_in"> settings </span>values</span><br><span class="line"> shell Interactive scraping console</span><br><span class="line"> startproject Create new project</span><br><span class="line"> version <span class="builtin-name">Print</span> Scrapy version</span><br><span class="line"> view Open URL <span class="keyword">in</span> browser, as seen by Scrapy</span><br><span class="line"></span><br><span class="line"> [ more ] More commands available when <span class="builtin-name">run</span> <span class="keyword">from</span> project directory</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>截图如下 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/2015-02-12-010022-的屏幕截图.png" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/2015-02-12-010022-的屏幕截图.png" alt="2015-02-12 01:00:22 的屏幕截图"></a> 如有问题，欢迎留言！祝各位小伙伴顺利安装！</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-17 01:02:41" itemprop="dateCreated datePublished" datetime="2015-02-17T01:02:41+08:00">2015-02-17</time>
                </span>
                <span id="/912.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫进阶三之Scrapy框架安装配置" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>2k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>2 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/977.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/977.html" class="post-title-link" itemprop="url">Python爬虫入门七之正则表达式</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>在前面我们已经搞定了怎样获取页面的内容，不过还差一步，这么多杂乱的代码夹杂文字我们怎样把它提取出来整理呢？下面就开始介绍一个十分强大的工具，正则表达式！</p>
                  <h2 id="1-了解正则表达式"><a href="#1-了解正则表达式" class="headerlink" title="1.了解正则表达式"></a>1.了解正则表达式</h2>
                  <blockquote>
                    <p>正则表达式是对字符串操作的一种逻辑公式，就是用事先定义好的一些特定字符、及这些特定字符的组合，组成一个“规则字符串”，这个“规则字符串”用来表达对字符串的一种过滤逻辑。</p>
                  </blockquote>
                  <p>正则表达式是用来匹配字符串非常强大的工具，在其他编程语言中同样有正则表达式的概念，Python同样不例外，利用了正则表达式，我们想要从返回的页面内容提取出我们想要的内容就易如反掌了。</p>
                  <blockquote>
                    <p>正则表达式的大致匹配过程是： 1.依次拿出表达式和文本中的字符比较， 2.如果每一个字符都能匹配，则匹配成功；一旦有匹配不成功的字符则匹配失败。 3.如果表达式中有量词或边界，这个过程会稍微有一些不同。</p>
                  </blockquote>
                  <h2 id="2-正则表达式的语法规则"><a href="#2-正则表达式的语法规则" class="headerlink" title="2.正则表达式的语法规则"></a>2.正则表达式的语法规则</h2>
                  <p>下面是Python中正则表达式的一些匹配规则，图片资料来自CSDN <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20130515113723855.png" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/20130515113723855-e1424095177180.png" alt="20130515113723855"></a></p>
                  <h2 id="3-正则表达式相关注解"><a href="#3-正则表达式相关注解" class="headerlink" title="3.正则表达式相关注解"></a>3.正则表达式相关注解</h2>
                  <h3 id="（1）数量词的贪婪模式与非贪婪模式"><a href="#（1）数量词的贪婪模式与非贪婪模式" class="headerlink" title="（1）数量词的贪婪模式与非贪婪模式"></a>（1）数量词的贪婪模式与非贪婪模式</h3>
                  <p>正则表达式通常用于在文本中查找匹配的字符串。Python里数量词默认是贪婪的（在少数语言里也可能是默认非贪婪），总是尝试匹配尽可能多的字符；非贪婪的则相反，总是尝试匹配尽可能少的字符。例如：正则表达式”ab<em>“如果用于查找”abbbc”，将找到”abbb”。而如果使用非贪婪的数量词”ab</em>?”，将找到”a”。 注：我们一般使用非贪婪模式来提取。</p>
                  <h3 id="（2）反斜杠问题"><a href="#（2）反斜杠问题" class="headerlink" title="（2）反斜杠问题"></a>（2）反斜杠问题</h3>
                  <p>与大多数编程语言相同，正则表达式里使用”\“作为转义字符，这就可能造成反斜杠困扰。假如你需要匹配文本中的字符”\“，那么使用编程语言表示的正则表达式里将需要4个反斜杠”\\\\“：前两个和后两个分别用于在编程语言里转义成反斜杠，转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。 Python里的原生字符串很好地解决了这个问题，这个例子中的正则表达式可以使用r”\\“表示。同样，匹配一个数字的”\\d”可以写成r”\d”。有了原生字符串，妈妈也不用担心是不是漏写了反斜杠，写出来的表达式也更直观勒。</p>
                  <h2 id="4-Python-Re模块"><a href="#4-Python-Re模块" class="headerlink" title="4.Python Re模块"></a>4.Python Re模块</h2>
                  <p>Python 自带了re模块，它提供了对正则表达式的支持。主要用到的方法列举如下</p>
                  <figure class="highlight css">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">#返回<span class="selector-tag">pattern</span>对象</span><br><span class="line"><span class="selector-tag">re</span><span class="selector-class">.compile</span>(<span class="selector-tag">string</span><span class="selector-attr">[,flag]</span>)  </span><br><span class="line">#以下为匹配所用函数</span><br><span class="line"><span class="selector-tag">re</span><span class="selector-class">.match</span>(<span class="selector-tag">pattern</span>, <span class="selector-tag">string</span><span class="selector-attr">[, flags]</span>)</span><br><span class="line"><span class="selector-tag">re</span><span class="selector-class">.search</span>(<span class="selector-tag">pattern</span>, <span class="selector-tag">string</span><span class="selector-attr">[, flags]</span>)</span><br><span class="line"><span class="selector-tag">re</span><span class="selector-class">.split</span>(<span class="selector-tag">pattern</span>, <span class="selector-tag">string</span><span class="selector-attr">[, maxsplit]</span>)</span><br><span class="line"><span class="selector-tag">re</span><span class="selector-class">.findall</span>(<span class="selector-tag">pattern</span>, <span class="selector-tag">string</span><span class="selector-attr">[, flags]</span>)</span><br><span class="line"><span class="selector-tag">re</span><span class="selector-class">.finditer</span>(<span class="selector-tag">pattern</span>, <span class="selector-tag">string</span><span class="selector-attr">[, flags]</span>)</span><br><span class="line"><span class="selector-tag">re</span><span class="selector-class">.sub</span>(<span class="selector-tag">pattern</span>, <span class="selector-tag">repl</span>, <span class="selector-tag">string</span><span class="selector-attr">[, count]</span>)</span><br><span class="line"><span class="selector-tag">re</span><span class="selector-class">.subn</span>(<span class="selector-tag">pattern</span>, <span class="selector-tag">repl</span>, <span class="selector-tag">string</span><span class="selector-attr">[, count]</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>在介绍这几个方法之前，我们先来介绍一下pattern的概念，pattern可以理解为一个匹配模式，那么我们怎么获得这个匹配模式呢？很简单，我们需要利用re.compile方法就可以。例如</p>
                  <figure class="highlight awk">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">pattern = re.compile(<span class="string">r'hello'</span>)</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>在参数中我们传入了原生字符串对象，通过compile方法编译生成一个pattern对象，然后我们利用这个对象来进行进一步的匹配。 另外大家可能注意到了另一个参数 flags，在这里解释一下这个参数的含义： 参数flag是匹配模式，取值可以使用按位或运算符’|’表示同时生效，比如re.I | re.M。 可选值有：</p>
                  <figure class="highlight livescript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">• re.I(全拼：IGNORECASE): 忽略大小写（括号内是完整写法，下同）</span><br><span class="line">• re.M(全拼：MULTILINE): 多行模式，改变<span class="string">'^'</span>和<span class="string">'$'</span>的行为（参见上图）</span><br><span class="line">• re.S(全拼：DOTALL): 点任意匹配模式，改变<span class="string">'.'</span>的行为</span><br><span class="line">• re.L(全拼：LOCALE): 使预定字符类 <span class="string">\w</span> <span class="string">\W</span> <span class="string">\b</span> <span class="string">\B</span> <span class="string">\s</span> <span class="string">\S</span> 取决于当前区域设定</span><br><span class="line">• re.U(全拼：UNICODE): 使预定字符类 <span class="string">\w</span> <span class="string">\W</span> <span class="string">\b</span> <span class="string">\B</span> <span class="string">\s</span> <span class="string">\S</span> <span class="string">\d</span> <span class="string">\D</span> 取决于unicode定义的字符属性</span><br><span class="line">• re.X(全拼：VERBOSE): 详细模式。这个模式下正则表达式可以是多行，忽略空白字符，并可以加入注释。</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>在刚才所说的另外几个方法例如 re.match 里我们就需要用到这个pattern了，下面我们一一介绍。</p>
                  <blockquote>
                    <p>注：以下七个方法中的flags同样是代表匹配模式的意思，如果在pattern生成时已经指明了flags，那么在下面的方法中就不需要传入这个参数了。</p>
                  </blockquote>
                  <h3 id="（1）re-match-pattern-string-flags"><a href="#（1）re-match-pattern-string-flags" class="headerlink" title="（1）re.match(pattern, string[, flags])"></a>（1）re.match(pattern, string[, flags])</h3>
                  <p>这个方法将会从string（我们要匹配的字符串）的开头开始，尝试匹配pattern，一直向后匹配，如果遇到无法匹配的字符，立即返回None，如果匹配未结束已经到达string的末尾，也会返回None。两个结果均表示匹配失败，否则匹配pattern成功，同时匹配终止，不再对string向后匹配。下面我们通过一个例子理解一下</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">__author__ = <span class="string">'CQC'</span></span><br><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#导入re模块</span></span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将正则表达式编译成Pattern对象，注意hello前面的r的意思是“原生字符串”</span></span><br><span class="line">pattern = re.compile(<span class="string">r'hello'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用re.match匹配文本，获得匹配结果，无法匹配时将返回None</span></span><br><span class="line">result1 = re.match(pattern,<span class="string">'hello'</span>)</span><br><span class="line">result2 = re.match(pattern,<span class="string">'helloo CQC!'</span>)</span><br><span class="line">result3 = re.match(pattern,<span class="string">'helo CQC!'</span>)</span><br><span class="line">result4 = re.match(pattern,<span class="string">'hello CQC!'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">#如果1匹配成功</span></span><br><span class="line"><span class="keyword">if</span> result1:</span><br><span class="line">    <span class="comment"># 使用Match获得分组信息</span></span><br><span class="line">    <span class="keyword">print</span> result1.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'1匹配失败！'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#如果2匹配成功</span></span><br><span class="line"><span class="keyword">if</span> result2:</span><br><span class="line">    <span class="comment"># 使用Match获得分组信息</span></span><br><span class="line">    <span class="keyword">print</span> result2.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'2匹配失败！'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#如果3匹配成功</span></span><br><span class="line"><span class="keyword">if</span> result3:</span><br><span class="line">    <span class="comment"># 使用Match获得分组信息</span></span><br><span class="line">    <span class="keyword">print</span> result3.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'3匹配失败！'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#如果4匹配成功</span></span><br><span class="line"><span class="keyword">if</span> result4:</span><br><span class="line">    <span class="comment"># 使用Match获得分组信息</span></span><br><span class="line">    <span class="keyword">print</span> result4.group()</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'4匹配失败！'</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">hello</span><br><span class="line">hello</span><br><span class="line"><span class="number">3</span>匹配失败！</span><br><span class="line">hello</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>匹配分析 1.第一个匹配，pattern正则表达式为’hello’，我们匹配的目标字符串string也为hello，从头至尾完全匹配，匹配成功。 2.第二个匹配，string为helloo CQC，从string头开始匹配pattern完全可以匹配，pattern匹配结束，同时匹配终止，后面的o CQC不再匹配，返回匹配成功的信息。 3.第三个匹配，string为helo CQC，从string头开始匹配pattern，发现到 ‘o’ 时无法完成匹配，匹配终止，返回None 4.第四个匹配，同第二个匹配原理，即使遇到了空格符也不会受影响。 我们还看到最后打印出了result.group()，这个是什么意思呢？下面我们说一下关于match对象的的属性和方法 Match对象是一次匹配的结果，包含了很多关于此次匹配的信息，可以使用Match提供的可读属性或方法来获取这些信息。</p>
                  <blockquote>
                    <p>属性： 1.string: 匹配时使用的文本。 2.re: 匹配时使用的Pattern对象。 3.pos: 文本中正则表达式开始搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。 4.endpos: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。 5.lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组，将为None。 6.lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组，将为None。 方法： 1.group([group1, …]): 获得一个或多个分组截获的字符串；指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名；编号0代表整个匹配的子串；不填写参数时，返回group(0)；没有截获字符串的组返回None；截获了多次的组返回最后一次截获的子串。 2.groups([default]): 以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代，默认为None。 3.groupdict([default]): 返回以有别名的组的别名为键、以该组截获的子串为值的字典，没有别名的组不包含在内。default含义同上。 4.start([group]): 返回指定的组截获的子串在string中的起始索引（子串第一个字符的索引）。group默认值为0。 5.end([group]): 返回指定的组截获的子串在string中的结束索引（子串最后一个字符的索引+1）。group默认值为0。 6.span([group]): 返回(start(group), end(group))。 7.expand(template): 将匹配到的分组代入template中然后返回。template中可以使用\id或\g、\g引用分组，但不能使用编号0。\id与\g是等价的；但\10将被认为是第10个分组，如果你想表达\1之后是字符’0’，只能使用\g0。</p>
                  </blockquote>
                  <p>下面我们用一个例子来体会一下</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment"># -*- coding: utf-8 -*-</span></span><br><span class="line"><span class="comment">#一个简单的match实例</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="comment"># 匹配如下内容：单词+空格+单词+任意字符</span></span><br><span class="line">m = re.match(<span class="string">r'(\w+) (\w+)(?P&lt;sign&gt;.*)'</span>, <span class="string">'hello world!'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.string:"</span>, m.string</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.re:"</span>, m.re</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.pos:"</span>, m.pos</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.endpos:"</span>, m.endpos</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.lastindex:"</span>, m.lastindex</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.lastgroup:"</span>, m.lastgroup</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.group():"</span>, m.group()</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.group(1,2):"</span>, m.group(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.groups():"</span>, m.groups()</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.groupdict():"</span>, m.groupdict()</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.start(2):"</span>, m.start(<span class="number">2</span>)</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.end(2):"</span>, m.end(<span class="number">2</span>)</span><br><span class="line"><span class="keyword">print</span> <span class="string">"m.span(2):"</span>, m.span(<span class="number">2</span>)</span><br><span class="line"><span class="keyword">print</span> <span class="string">r"m.expand(r'\g \g\g'):"</span>, m.expand(<span class="string">r'\2 \1\3'</span>)</span><br><span class="line"> </span><br><span class="line"><span class="comment">### output ###</span></span><br><span class="line"><span class="comment"># m.string: hello world!</span></span><br><span class="line"><span class="comment"># m.re: </span></span><br><span class="line"><span class="comment"># m.pos: 0</span></span><br><span class="line"><span class="comment"># m.endpos: 12</span></span><br><span class="line"><span class="comment"># m.lastindex: 3</span></span><br><span class="line"><span class="comment"># m.lastgroup: sign</span></span><br><span class="line"><span class="comment"># m.group(1,2): ('hello', 'world')</span></span><br><span class="line"><span class="comment"># m.groups(): ('hello', 'world', '!')</span></span><br><span class="line"><span class="comment"># m.groupdict(): &#123;'sign': '!'&#125;</span></span><br><span class="line"><span class="comment"># m.start(2): 6</span></span><br><span class="line"><span class="comment"># m.end(2): 11</span></span><br><span class="line"><span class="comment"># m.span(2): (6, 11)</span></span><br><span class="line"><span class="comment"># m.expand(r'\2 \1\3'): world hello!</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="（2）re-search-pattern-string-flags"><a href="#（2）re-search-pattern-string-flags" class="headerlink" title="（2）re.search(pattern, string[, flags])"></a>（2）re.search(pattern, string[, flags])</h3>
                  <p>search方法与match方法极其类似，区别在于match()函数只检测re是不是在string的开始位置匹配，search()会扫描整个string查找匹配，match（）只有在0位置匹配成功的话才有返回，如果不是开始位置匹配成功的话，match()就返回None。同样，search方法的返回对象同样match()返回对象的方法和属性。我们用一个例子感受一下</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="comment">#导入re模块</span></span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将正则表达式编译成Pattern对象</span></span><br><span class="line">pattern = re.compile(<span class="string">r'world'</span>)</span><br><span class="line"><span class="comment"># 使用search()查找匹配的子串，不存在能匹配的子串时将返回None</span></span><br><span class="line"><span class="comment"># 这个例子中使用match()无法成功匹配</span></span><br><span class="line">match = re.search(pattern,<span class="string">'hello world!'</span>)</span><br><span class="line"><span class="keyword">if</span> match:</span><br><span class="line">    <span class="comment"># 使用Match获得分组信息</span></span><br><span class="line">    <span class="keyword">print</span> match.group()</span><br><span class="line"><span class="comment">### 输出 ###</span></span><br><span class="line"><span class="comment"># world</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="（3）re-split-pattern-string-maxsplit"><a href="#（3）re-split-pattern-string-maxsplit" class="headerlink" title="（3）re.split(pattern, string[, maxsplit])"></a>（3）re.split(pattern, string[, maxsplit])</h3>
                  <p>按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数，不指定将全部分割。我们通过下面的例子感受一下。</p>
                  <figure class="highlight clean">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line">pattern = re.compile(r<span class="string">'\d+'</span>)</span><br><span class="line">print re.split(pattern,<span class="string">'one1two2three3four4'</span>)</span><br><span class="line"></span><br><span class="line">### 输出 ###</span><br><span class="line"># [<span class="string">'one'</span>, <span class="string">'two'</span>, <span class="string">'three'</span>, <span class="string">'four'</span>, <span class="string">''</span>]</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="（4）re-findall-pattern-string-flags"><a href="#（4）re-findall-pattern-string-flags" class="headerlink" title="（4）re.findall(pattern, string[, flags])"></a>（4）re.findall(pattern, string[, flags])</h3>
                  <p>搜索string，以列表形式返回全部能匹配的子串。我们通过这个例子来感受一下</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line">pattern = re.compile(<span class="string">r'\d+'</span>)</span><br><span class="line"><span class="keyword">print</span> re.findall(pattern,<span class="string">'one1two2three3four4'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">### 输出 ###</span></span><br><span class="line"><span class="comment"># ['1', '2', '3', '4']</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="（5）re-finditer-pattern-string-flags"><a href="#（5）re-finditer-pattern-string-flags" class="headerlink" title="（5）re.finditer(pattern, string[, flags])"></a>（5）re.finditer(pattern, string[, flags])</h3>
                  <p>搜索string，返回一个顺序访问每一个匹配结果（Match对象）的迭代器。我们通过下面的例子来感受一下</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line">pattern = re.compile(<span class="string">r'\d+'</span>)</span><br><span class="line"><span class="keyword">for</span> m <span class="keyword">in</span> re.finditer(pattern,<span class="string">'one1two2three3four4'</span>):</span><br><span class="line">    <span class="keyword">print</span> m.group(),</span><br><span class="line"></span><br><span class="line"><span class="comment">### 输出 ###</span></span><br><span class="line"><span class="comment"># 1 2 3 4</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="（6）re-sub-pattern-repl-string-count"><a href="#（6）re-sub-pattern-repl-string-count" class="headerlink" title="（6）re.sub(pattern, repl, string[, count])"></a>（6）re.sub(pattern, repl, string[, count])</h3>
                  <p>使用repl替换string中每一个匹配的子串后返回替换后的字符串。 当repl是一个字符串时，可以使用\id或\g、\g引用分组，但不能使用编号0。 当repl是一个方法时，这个方法应当只接受一个参数（Match对象），并返回一个字符串用于替换（返回的字符串中不能再引用分组）。 count用于指定最多替换次数，不指定时全部替换。</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line">pattern = re.compile(<span class="string">r'(\w+) (\w+)'</span>)</span><br><span class="line">s = <span class="string">'i say, hello world!'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">print</span> re.sub(pattern,<span class="string">r'\2 \1'</span>, s)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">func</span><span class="params">(m)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> m.group(<span class="number">1</span>).title() + <span class="string">' '</span> + m.group(<span class="number">2</span>).title()</span><br><span class="line"></span><br><span class="line"><span class="keyword">print</span> re.sub(pattern,func, s)</span><br><span class="line"></span><br><span class="line"><span class="comment">### output ###</span></span><br><span class="line"><span class="comment"># say i, world hello!</span></span><br><span class="line"><span class="comment"># I Say, Hello World!</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="（7）re-subn-pattern-repl-string-count"><a href="#（7）re-subn-pattern-repl-string-count" class="headerlink" title="（7）re.subn(pattern, repl, string[, count])"></a>（7）re.subn(pattern, repl, string[, count])</h3>
                  <p>返回 (sub(repl, string[, count]), 替换次数)。</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"> </span><br><span class="line">pattern = re.compile(<span class="string">r'(\w+) (\w+)'</span>)</span><br><span class="line">s = <span class="string">'i say, hello world!'</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">print</span> re.subn(pattern,<span class="string">r'\2 \1'</span>, s)</span><br><span class="line"> </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">func</span><span class="params">(m)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> m.group(<span class="number">1</span>).title() + <span class="string">' '</span> + m.group(<span class="number">2</span>).title()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">print</span> re.subn(pattern,func, s)</span><br><span class="line"> </span><br><span class="line"><span class="comment">### output ###</span></span><br><span class="line"><span class="comment"># ('say i, world hello!', 2)</span></span><br><span class="line"><span class="comment"># ('I Say, Hello World!', 2)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h2 id="5-Python-Re模块的另一种使用方式"><a href="#5-Python-Re模块的另一种使用方式" class="headerlink" title="5.Python Re模块的另一种使用方式"></a>5.Python Re模块的另一种使用方式</h2>
                  <p>在上面我们介绍了7个工具方法，例如match，search等等，不过调用方式都是 re.match，re.search的方式，其实还有另外一种调用方式，可以通过pattern.match，pattern.search调用，这样调用便不用将pattern作为第一个参数传入了，大家想怎样调用皆可。 函数API列表</p>
                  <figure class="highlight vim">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">match</span>(<span class="built_in">string</span>[, pos[, endpos]]) | re.<span class="keyword">match</span>(pattern, <span class="built_in">string</span>[, flags])</span><br><span class="line"><span class="built_in">search</span>(<span class="built_in">string</span>[, pos[, endpos]]) | re.<span class="built_in">search</span>(pattern, <span class="built_in">string</span>[, flags])</span><br><span class="line"><span class="keyword">split</span>(<span class="built_in">string</span>[, maxsplit]) | re.<span class="keyword">split</span>(pattern, <span class="built_in">string</span>[, maxsplit])</span><br><span class="line">findall(<span class="built_in">string</span>[, pos[, endpos]]) | re.findall(pattern, <span class="built_in">string</span>[, flags])</span><br><span class="line">finditer(<span class="built_in">string</span>[, pos[, endpos]]) | re.finditer(pattern, <span class="built_in">string</span>[, flags])</span><br><span class="line">sub(repl, <span class="built_in">string</span>[, <span class="built_in">count</span>]) | re.sub(pattern, repl, <span class="built_in">string</span>[, <span class="built_in">count</span>])</span><br><span class="line">subn(repl, <span class="built_in">string</span>[, <span class="built_in">count</span>]) |re.sub(pattern, repl, <span class="built_in">string</span>[, <span class="built_in">count</span>])</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>具体的调用方法不必详说了，原理都类似，只是参数的变化不同。小伙伴们尝试一下吧~ 小伙伴们加油，即使这一节看得云里雾里的也没关系，接下来我们会通过一些实战例子来帮助大家熟练掌握正则表达式的。 参考文章：此文章部分内容出自 <a href="http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html" target="_blank" rel="noopener">CNBlogs</a></p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-15 23:30:22" itemprop="dateCreated datePublished" datetime="2015-02-15T23:30:22+08:00">2015-02-15</time>
                </span>
                <span id="/977.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫入门七之正则表达式" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>7.5k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>7 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/968.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/968.html" class="post-title-link" itemprop="url">Python爬虫入门六之Cookie的使用</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>大家好哈，上一节我们研究了一下爬虫的异常处理问题，那么接下来我们一起来看一下Cookie的使用。 为什么要使用Cookie呢？ Cookie，指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据（通常经过加密） 比如说有些网站需要登录后才能访问某个页面，在登录之前，你想抓取某个页面内容是不允许的。那么我们可以利用Urllib2库保存我们登录的Cookie，然后再抓取其他页面就达到目的了。 在此之前呢，我们必须先介绍一个opener的概念。</p>
                  <h2 id="1-Opener"><a href="#1-Opener" class="headerlink" title="1.Opener"></a>1.Opener</h2>
                  <p>当你获取一个URL你使用一个opener(一个urllib2.OpenerDirector的实例)。在前面，我们都是使用的默认的opener，也就是urlopen。它是一个特殊的opener，可以理解成opener的一个特殊实例，传入的参数仅仅是url，data，timeout。 如果我们需要用到Cookie，只用这个opener是不能达到目的的，所以我们需要创建更一般的opener来实现对Cookie的设置。</p>
                  <h2 id="2-Cookielib"><a href="#2-Cookielib" class="headerlink" title="2.Cookielib"></a>2.Cookielib</h2>
                  <p>cookielib模块的主要作用是提供可存储cookie的对象，以便于与urllib2模块配合使用来访问Internet资源。Cookielib模块非常强大，我们可以利用本模块的CookieJar类的对象来捕获cookie并在后续连接请求时重新发送，比如可以实现模拟登录功能。该模块主要的对象有CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar。 它们的关系：CookieJar ——派生——&gt;FileCookieJar ——派生——-&gt;MozillaCookieJar和LWPCookieJar</p>
                  <h3 id="1）获取Cookie保存到变量"><a href="#1）获取Cookie保存到变量" class="headerlink" title="1）获取Cookie保存到变量"></a>1）获取Cookie保存到变量</h3>
                  <p>首先，我们先利用CookieJar对象实现获取cookie的功能，存储到变量中，先来感受一下</p>
                  <figure class="highlight properties">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="attr">import</span> <span class="string">urllib2</span></span><br><span class="line"><span class="attr">import</span> <span class="string">cookielib</span></span><br><span class="line"><span class="comment">#声明一个CookieJar对象实例来保存cookie</span></span><br><span class="line"><span class="attr">cookie</span> = <span class="string">cookielib.CookieJar()</span></span><br><span class="line"><span class="comment">#利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器</span></span><br><span class="line"><span class="attr">handler</span>=<span class="string">urllib2.HTTPCookieProcessor(cookie)</span></span><br><span class="line"><span class="comment">#通过handler来构建opener</span></span><br><span class="line"><span class="attr">opener</span> = <span class="string">urllib2.build_opener(handler)</span></span><br><span class="line"><span class="comment">#此处的open方法同urllib2的urlopen方法，也可以传入request</span></span><br><span class="line"><span class="attr">response</span> = <span class="string">opener.open('http://www.baidu.com')</span></span><br><span class="line"><span class="attr">for</span> <span class="string">item in cookie:</span></span><br><span class="line">    <span class="attr">print</span> <span class="string">'Name = '+item.name</span></span><br><span class="line">    <span class="attr">print</span> <span class="string">'Value = '+item.value</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>我们使用以上方法将cookie保存到变量中，然后打印出了cookie中的值，运行结果如下</p>
                  <figure class="highlight ini">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="attr">Name</span> = BAIDUID</span><br><span class="line"><span class="attr">Value</span> = B07B663B645729F11F659C02AAE65B4C:FG=<span class="number">1</span></span><br><span class="line"><span class="attr">Name</span> = BAIDUPSID</span><br><span class="line"><span class="attr">Value</span> = B07B663B645729F11F659C02AAE65B4C</span><br><span class="line"><span class="attr">Name</span> = H_PS_PSSID</span><br><span class="line"><span class="attr">Value</span> = <span class="number">12527_11076_1438_10633</span></span><br><span class="line"><span class="attr">Name</span> = BDSVRTM</span><br><span class="line"><span class="attr">Value</span> = <span class="number">0</span></span><br><span class="line"><span class="attr">Name</span> = BD_HOME</span><br><span class="line"><span class="attr">Value</span> = <span class="number">0</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <h3 id="2）保存Cookie到文件"><a href="#2）保存Cookie到文件" class="headerlink" title="2）保存Cookie到文件"></a>2）保存Cookie到文件</h3>
                  <p>在上面的方法中，我们将cookie保存到了cookie这个变量中，如果我们想将cookie保存到文件中该怎么做呢？这时，我们就要用到 FileCookieJar这个对象了，在这里我们使用它的子类MozillaCookieJar来实现Cookie的保存</p>
                  <figure class="highlight nix">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="built_in">import</span> cookielib</span><br><span class="line"><span class="built_in">import</span> urllib2</span><br><span class="line"></span><br><span class="line"><span class="comment">#设置保存cookie的文件，同级目录下的cookie.txt</span></span><br><span class="line"><span class="attr">filename</span> = 'cookie.txt'</span><br><span class="line"><span class="comment">#声明一个MozillaCookieJar对象实例来保存cookie，之后写入文件</span></span><br><span class="line"><span class="attr">cookie</span> = cookielib.MozillaCookieJar(filename)</span><br><span class="line"><span class="comment">#利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器</span></span><br><span class="line"><span class="attr">handler</span> = urllib2.HTTPCookieProcessor(cookie)</span><br><span class="line"><span class="comment">#通过handler来构建opener</span></span><br><span class="line"><span class="attr">opener</span> = urllib2.build_opener(handler)</span><br><span class="line"><span class="comment">#创建一个请求，原理同urllib2的urlopen</span></span><br><span class="line"><span class="attr">response</span> = opener.open(<span class="string">"http://www.baidu.com"</span>)</span><br><span class="line"><span class="comment">#保存cookie到文件</span></span><br><span class="line">cookie.save(<span class="attr">ignore_discard=True,</span> <span class="attr">ignore_expires=True)</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>关于最后save方法的两个参数在此说明一下： 官方解释如下：</p>
                  <blockquote>
                    <p><em>ignore_discard: save even cookies set to be discarded. </em> <em>ignore_expires: save even cookies that have expiredThe file is overwritten if it already exists</em></p>
                  </blockquote>
                  <p>由此可见，ignore_discard的意思是即使cookies将被丢弃也将它保存下来，ignore_expires的意思是如果在该文件中cookies已经存在，则覆盖原文件写入，在这里，我们将这两个全部设置为True。运行之后，cookies将被保存到cookie.txt文件中，我们查看一下内容，附图如下 <a href="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150215215136.jpg" target="_blank" rel="noopener"><img src="http://qiniu.cuiqingcai.com/wp-content/uploads/2015/02/QQ截图20150215215136.jpg" alt="QQ截图20150215215136"></a></p>
                  <h3 id="3）从文件中获取Cookie并访问"><a href="#3）从文件中获取Cookie并访问" class="headerlink" title="3）从文件中获取Cookie并访问"></a>3）从文件中获取Cookie并访问</h3>
                  <p>那么我们已经做到把Cookie保存到文件中了，如果以后想使用，可以利用下面的方法来读取cookie并访问网站，感受一下</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">import cookielib</span><br><span class="line">import urllib2</span><br><span class="line"></span><br><span class="line"><span class="comment">#创建MozillaCookieJar实例对象</span></span><br><span class="line">cookie = cookielib.MozillaCookieJar()</span><br><span class="line"><span class="comment">#从文件中读取cookie内容到变量</span></span><br><span class="line">cookie.load(<span class="string">'cookie.txt'</span>, <span class="attribute">ignore_discard</span>=<span class="literal">True</span>, <span class="attribute">ignore_expires</span>=<span class="literal">True</span>)</span><br><span class="line"><span class="comment">#创建请求的request</span></span><br><span class="line">req = urllib2.Request(<span class="string">"http://www.baidu.com"</span>)</span><br><span class="line"><span class="comment">#利用urllib2的build_opener方法创建一个opener</span></span><br><span class="line">opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))</span><br><span class="line">response = opener.open(req)</span><br><span class="line"><span class="builtin-name">print</span> response.read()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>设想，如果我们的 cookie.txt 文件中保存的是某个人登录百度的cookie，那么我们提取出这个cookie文件内容，就可以用以上方法模拟这个人的账号登录百度。</p>
                  <h3 id="4）利用cookie模拟网站登录"><a href="#4）利用cookie模拟网站登录" class="headerlink" title="4）利用cookie模拟网站登录"></a>4）利用cookie模拟网站登录</h3>
                  <p>下面我们以我们学校的教育系统为例，利用cookie实现模拟登录，并将cookie信息保存到文本文件中，来感受一下cookie大法吧！ 注意：密码我改了啊，别偷偷登录本宫的选课系统 o(╯□╰)o</p>
                  <figure class="highlight routeros">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">import urllib</span><br><span class="line">import urllib2</span><br><span class="line">import cookielib</span><br><span class="line"></span><br><span class="line">filename = <span class="string">'cookie.txt'</span></span><br><span class="line"><span class="comment">#声明一个MozillaCookieJar对象实例来保存cookie，之后写入文件</span></span><br><span class="line">cookie = cookielib.MozillaCookieJar(filename)</span><br><span class="line">opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))</span><br><span class="line">postdata = urllib.urlencode(&#123;</span><br><span class="line">			<span class="string">'stuid'</span>:<span class="string">'201200131012'</span>,</span><br><span class="line">			<span class="string">'pwd'</span>:<span class="string">'23342321'</span></span><br><span class="line">		&#125;)</span><br><span class="line"><span class="comment">#登录教务系统的URL</span></span><br><span class="line">loginUrl = <span class="string">'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bks_login2.login'</span></span><br><span class="line"><span class="comment">#模拟登录，并把cookie保存到变量</span></span><br><span class="line">result = opener.open(loginUrl,postdata)</span><br><span class="line"><span class="comment">#保存cookie到cookie.txt中</span></span><br><span class="line">cookie.save(<span class="attribute">ignore_discard</span>=<span class="literal">True</span>, <span class="attribute">ignore_expires</span>=<span class="literal">True</span>)</span><br><span class="line"><span class="comment">#利用cookie请求访问另一个网址，此网址是成绩查询网址</span></span><br><span class="line">gradeUrl = <span class="string">'http://jwxt.sdu.edu.cn:7890/pls/wwwbks/bkscjcx.curscopre'</span></span><br><span class="line"><span class="comment">#请求访问成绩查询网址</span></span><br><span class="line">result = opener.open(gradeUrl)</span><br><span class="line"><span class="builtin-name">print</span> result.read()</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>以上程序的原理如下 创建一个带有cookie的opener，在访问登录的URL时，将登录后的cookie保存下来，然后利用这个cookie来访问其他网址。 如登录之后才能查看的成绩查询呀，本学期课表呀等等网址，模拟登录就这么实现啦，是不是很酷炫？ 好，小伙伴们要加油哦！我们现在可以顺利获取网站信息了，接下来就是把网站里面有效内容提取出来，下一节我们去会会正则表达式！</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-15 01:01:35" itemprop="dateCreated datePublished" datetime="2015-02-15T01:01:35+08:00">2015-02-15</time>
                </span>
                <span id="/968.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫入门六之Cookie的使用" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>3.9k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>4 分钟</span>
                </span>
              </div>
            </article>
            <article itemscope itemtype="http://schema.org/Article" class="post-block index" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/961.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h2 class="post-title" itemprop="name headline">
                  <a class="label"> Python <i class="label-arrow"></i>
                  </a>
                  <a href="/961.html" class="post-title-link" itemprop="url">Python爬虫入门五之URLError异常处理</a>
                </h2>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="thumb">
                  <img itemprop="contentUrl" class="random">
                </div>
                <div class="excerpt">
                  <p>
                  <p>大家好，本节在这里主要说的是URLError还有HTTPError，以及对它们的一些处理。</p>
                  <h2 id="1-URLError"><a href="#1-URLError" class="headerlink" title="1.URLError"></a>1.URLError</h2>
                  <p>首先解释下URLError可能产生的原因：</p>
                  <ul>
                    <li>网络无连接，即本机无法上网</li>
                    <li>连接不到特定的服务器</li>
                    <li>服务器不存在</li>
                  </ul>
                  <p>在代码中，我们需要用try-except语句来包围并捕获相应的异常。下面是一个例子，先感受下它的风骚</p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">import urllib2</span><br><span class="line"></span><br><span class="line">requset = urllib2.<span class="constructor">Request('<span class="params">http</span>:<span class="operator">/</span><span class="operator">/</span><span class="params">www</span>.<span class="params">xxxxx</span>.<span class="params">com</span>')</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    urllib2.urlopen(request)</span><br><span class="line">except urllib2.URLError, e:</span><br><span class="line">    print e.reason</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>我们利用了 urlopen方法访问了一个不存在的网址，运行结果如下：</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">[Errno <span class="number">11004</span>] getaddrinfo failed</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>它说明了错误代号是11004，错误原因是 getaddrinfo failed 2.HTTPError HTTPError是URLError的子类，在你利用urlopen方法发出一个请求时，服务器上都会对应一个应答对象response，其中它包含一个数字”状态码”。举个例子，假如response是一个”重定向”，需定位到别的地址获取文档，urllib2将对此进行处理。 其他不能处理的，urlopen会产生一个HTTPError，对应相应的状态吗，HTTP状态码表示HTTP协议所返回的响应的状态。下面将状态码归结如下：</p>
                  <blockquote>
                    <p>100：继续 客户端应当继续发送请求。客户端应当继续发送请求的剩余部分，或者如果请求已经完成，忽略这个响应。 101： 转换协议 在发送完这个响应最后的空行后，服务器将会切换到在Upgrade 消息头中定义的那些协议。只有在切换新的协议更有好处的时候才应该采取类似措施。 102：继续处理 由WebDAV（RFC 2518）扩展的状态码，代表处理将被继续执行。 200：请求成功 处理方式：获得响应的内容，进行处理 201：请求完成，结果是创建了新资源。新创建资源的URI可在响应的实体中得到 处理方式：爬虫中不会遇到 202：请求被接受，但处理尚未完成 处理方式：阻塞等待 204：服务器端已经实现了请求，但是没有返回新的信 息。如果客户是用户代理，则无须为此更新自身的文档视图。 处理方式：丢弃 300：该状态码不被HTTP/1.0的应用程序直接使用， 只是作为3XX类型回应的默认解释。存在多个可用的被请求资源。 处理方式：若程序中能够处理，则进行进一步处理，如果程序中不能处理，则丢弃 301：请求到的资源都会分配一个永久的URL，这样就可以在将来通过该URL来访问此资源 处理方式：重定向到分配的URL 302：请求到的资源在一个不同的URL处临时保存 处理方式：重定向到临时的URL 304：请求的资源未更新 处理方式：丢弃 400：非法请求 处理方式：丢弃 401：未授权 处理方式：丢弃 403：禁止 处理方式：丢弃 404：没有找到 处理方式：丢弃 500：服务器内部错误 服务器遇到了一个未曾预料的状况，导致了它无法完成对请求的处理。一般来说，这个问题都会在服务器端的源代码出现错误时出现。 501：服务器无法识别 服务器不支持当前请求所需要的某个功能。当服务器无法识别请求的方法，并且无法支持其对任何资源的请求。 502：错误网关 作为网关或者代理工作的服务器尝试执行请求时，从上游服务器接收到无效的响应。 503：服务出错 由于临时的服务器维护或者过载，服务器当前无法处理请求。这个状况是临时的，并且将在一段时间以后恢复。</p>
                  </blockquote>
                  <p>HTTPError实例产生后会有一个code属性，这就是是服务器发送的相关错误号。 因为urllib2可以为你处理重定向，也就是3开头的代号可以被处理，并且100-299范围的号码指示成功，所以你只能看到400-599的错误号码。 下面我们写一个例子来感受一下，捕获的异常是HTTPError，它会带有一个code属性，就是错误代号，另外我们又打印了reason属性，这是它的父类URLError的属性。</p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">import urllib2</span><br><span class="line"></span><br><span class="line">req = urllib2.<span class="constructor">Request('<span class="params">http</span>:<span class="operator">/</span><span class="operator">/</span><span class="params">blog</span>.<span class="params">csdn</span>.<span class="params">net</span><span class="operator">/</span><span class="params">cqcre</span>')</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    urllib2.urlopen(req)</span><br><span class="line">except urllib2.HTTPError, e:</span><br><span class="line">    print e.code</span><br><span class="line">    print e.reason</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>运行结果如下</p>
                  <figure class="highlight angelscript">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="number">403</span></span><br><span class="line">Forbidden</span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>错误代号是403，错误原因是Forbidden，说明服务器禁止访问。 我们知道，HTTPError的父类是URLError，根据编程经验，父类的异常应当写到子类异常的后面，如果子类捕获不到，那么可以捕获父类的异常，所以上述的代码可以这么改写</p>
                  <figure class="highlight python">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line"><span class="keyword">import</span> urllib2</span><br><span class="line"></span><br><span class="line">req = urllib2.Request(<span class="string">'http://blog.csdn.net/cqcre'</span>)</span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    urllib2.urlopen(req)</span><br><span class="line"><span class="keyword">except</span> urllib2.HTTPError, e:</span><br><span class="line">    <span class="keyword">print</span> e.code</span><br><span class="line"><span class="keyword">except</span> urllib2.URLError, e:</span><br><span class="line">    <span class="keyword">print</span> e.reason</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">"OK"</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>如果捕获到了HTTPError，则输出code，不会再处理URLError异常。如果发生的不是HTTPError，则会去捕获URLError异常，输出错误原因。 另外还可以加入 hasattr属性提前对属性进行判断，代码改写如下</p>
                  <figure class="highlight reasonml">
                    <table>
                      <tr>
                        <td class="gutter">
                          <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                        </td>
                        <td class="code">
                          <pre><span class="line">import urllib2</span><br><span class="line"></span><br><span class="line">req = urllib2.<span class="constructor">Request('<span class="params">http</span>:<span class="operator">/</span><span class="operator">/</span><span class="params">blog</span>.<span class="params">csdn</span>.<span class="params">net</span><span class="operator">/</span><span class="params">cqcre</span>')</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    urllib2.urlopen(req)</span><br><span class="line">except urllib2.URLError, e:</span><br><span class="line">    <span class="keyword">if</span> hasattr(e,<span class="string">"reason"</span>):</span><br><span class="line">        print e.reason</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    print <span class="string">"OK"</span></span><br></pre>
                        </td>
                      </tr>
                    </table>
                  </figure>
                  <p>首先对异常的属性进行判断，以免出现属性输出报错的现象。 以上，就是对URLError和HTTPError的相关介绍，以及相应的错误处理办法，小伙伴们加油！</p>
                  </p>
                </div>
              </div>
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-user"></i>
                  </span>
                  <span class="post-meta-item-text">作者</span>
                  <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>
                  <time title="创建时间：2015-02-14 01:02:04" itemprop="dateCreated datePublished" datetime="2015-02-14T01:02:04+08:00">2015-02-14</time>
                </span>
                <span id="/961.html" class="post-meta-item leancloud_visitors" data-flag-title="Python爬虫入门五之URLError异常处理" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="fa fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
                <span class="post-meta-item" title="本文字数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-file-word"></i>
                  </span>
                  <span class="post-meta-item-text">本文字数：</span>
                  <span>2.5k</span>
                </span>
                <span class="post-meta-item" title="阅读时长">
                  <span class="post-meta-item-icon">
                    <i class="far fa-clock"></i>
                  </span>
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                  <span>2 分钟</span>
                </span>
              </div>
            </article>
            <script>
              document.querySelectorAll('.random').forEach(item => item.src = "https://picsum.photos/id/" + Math.floor(Math.random() * Math.floor(300)) + "/200/133")

            </script>
            <nav class="pagination">
              <a class="extend prev" rel="prev" href="/page/27/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/27/">27</a><span class="page-number current">28</span><a class="page-number" href="/page/29/">29</a><span class="space">&hellip;</span><a class="page-number" href="/page/31/">31</a><a class="extend next" rel="next" href="/page/29/"><i class="fa fa-angle-right" aria-label="下一页"></i></a>
            </nav>
          </div>
          <script>
            window.addEventListener('tabs:register', () =>
            {
              let
              {
                activeClass
              } = CONFIG.comments;
              if (CONFIG.comments.storage)
              {
                activeClass = localStorage.getItem('comments_active') || activeClass;
              }
              if (activeClass)
              {
                let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
                if (activeTab)
                {
                  activeTab.click();
                }
              }
            });
            if (CONFIG.comments.storage)
            {
              window.addEventListener('tabs:click', event =>
              {
                if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
                let commentClass = event.target.classList[1];
                localStorage.setItem('comments_active', commentClass);
              });
            }

          </script>
        </div>
        <div class="toggle sidebar-toggle">
          <span class="toggle-line toggle-line-first"></span>
          <span class="toggle-line toggle-line-middle"></span>
          <span class="toggle-line toggle-line-last"></span>
        </div>
        <aside class="sidebar">
          <div class="sidebar-inner">
            <ul class="sidebar-nav motion-element">
              <li class="sidebar-nav-toc"> 文章目录 </li>
              <li class="sidebar-nav-overview"> 站点概览 </li>
            </ul>
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
            </div>
            <!--/noindex-->
            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <img class="site-author-image" itemprop="image" alt="崔庆才" src="/images/avatar.png">
                <p class="site-author-name" itemprop="name">崔庆才</p>
                <div class="site-description" itemprop="description">崔庆才的个人站点，记录生活的瞬间，分享学习的心得。</div>
              </div>
              <div class="site-state-wrap motion-element">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">
                      <span class="site-state-item-count">608</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">
                      <span class="site-state-item-count">24</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">
                      <span class="site-state-item-count">156</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author motion-element">
                <span class="links-of-author-item">
                  <a href="https://github.com/Germey" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Germey" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:cqc@cuiqingcai.com.com" title="邮件 → mailto:cqc@cuiqingcai.com.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>邮件</a>
                </span>
                <span class="links-of-author-item">
                  <a href="https://weibo.com/cuiqingcai" title="微博 → https:&#x2F;&#x2F;weibo.com&#x2F;cuiqingcai" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>微博</a>
                </span>
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/Germey" title="知乎 → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;Germey" rel="noopener" target="_blank"><i class="fa fa-magic fa-fw"></i>知乎</a>
                </span>
              </div>
            </div>
            <div style=" width: 100%;" class="sidebar-panel sidebar-panel-image sidebar-panel-active">
              <a href="https://tutorial.lengyue.video/?coupon=12ef4b1a-a3db-11ea-bb37-0242ac130002_cqx_850" target="_blank" rel="noopener">
                <img src="https://qiniu.cuiqingcai.com/bco2a.png" style=" width: 100%;">
              </a>
            </div>
            <div style=" width: 100%;" class="sidebar-panel sidebar-panel-image sidebar-panel-active">
              <a href="http://www.ipidea.net/?utm-source=cqc&utm-keyword=?cqc" target="_blank" rel="noopener">
                <img src="https://qiniu.cuiqingcai.com/0ywun.png" style=" width: 100%;">
              </a>
            </div>
            <div class="sidebar-panel sidebar-panel-tags sidebar-panel-active">
              <h4 class="name"> 标签云 </h4>
              <div class="content">
                <a href="/tags/2048/" style="font-size: 10px;">2048</a> <a href="/tags/API/" style="font-size: 10px;">API</a> <a href="/tags/Bootstrap/" style="font-size: 11.25px;">Bootstrap</a> <a href="/tags/CDN/" style="font-size: 10px;">CDN</a> <a href="/tags/CQC/" style="font-size: 10px;">CQC</a> <a href="/tags/CSS/" style="font-size: 10px;">CSS</a> <a href="/tags/CSS-%E5%8F%8D%E7%88%AC%E8%99%AB/" style="font-size: 10px;">CSS 反爬虫</a> <a href="/tags/CV/" style="font-size: 10px;">CV</a> <a href="/tags/Django/" style="font-size: 10px;">Django</a> <a href="/tags/Eclipse/" style="font-size: 11.25px;">Eclipse</a> <a href="/tags/FTP/" style="font-size: 10px;">FTP</a> <a href="/tags/Git/" style="font-size: 10px;">Git</a> <a href="/tags/GitHub/" style="font-size: 13.75px;">GitHub</a> <a href="/tags/HTML5/" style="font-size: 10px;">HTML5</a> <a href="/tags/Hexo/" style="font-size: 10px;">Hexo</a> <a href="/tags/IT/" style="font-size: 10px;">IT</a> <a href="/tags/JSP/" style="font-size: 10px;">JSP</a> <a href="/tags/JavaScript/" style="font-size: 10px;">JavaScript</a> <a href="/tags/K8s/" style="font-size: 10px;">K8s</a> <a href="/tags/LOGO/" style="font-size: 10px;">LOGO</a> <a href="/tags/Linux/" style="font-size: 10px;">Linux</a> <a href="/tags/MIUI/" style="font-size: 10px;">MIUI</a> <a href="/tags/MongoDB/" style="font-size: 10px;">MongoDB</a> <a href="/tags/Mysql/" style="font-size: 10px;">Mysql</a> <a href="/tags/NBA/" style="font-size: 10px;">NBA</a> <a href="/tags/PHP/" style="font-size: 11.25px;">PHP</a> <a href="/tags/PS/" style="font-size: 10px;">PS</a> <a href="/tags/Pathlib/" style="font-size: 10px;">Pathlib</a> <a href="/tags/PhantomJS/" style="font-size: 10px;">PhantomJS</a> <a href="/tags/Python/" style="font-size: 15px;">Python</a> <a href="/tags/Python3/" style="font-size: 12.5px;">Python3</a> <a href="/tags/Pythonic/" style="font-size: 10px;">Pythonic</a> <a href="/tags/QQ/" style="font-size: 10px;">QQ</a> <a href="/tags/Redis/" style="font-size: 10px;">Redis</a> <a href="/tags/SAE/" style="font-size: 10px;">SAE</a> <a href="/tags/SSH/" style="font-size: 10px;">SSH</a> <a href="/tags/SVG/" style="font-size: 10px;">SVG</a> <a href="/tags/Scrapy/" style="font-size: 10px;">Scrapy</a> <a href="/tags/Scrapy-redis/" style="font-size: 10px;">Scrapy-redis</a> <a href="/tags/Scrapy%E5%88%86%E5%B8%83%E5%BC%8F/" style="font-size: 10px;">Scrapy分布式</a> <a href="/tags/Selenium/" style="font-size: 10px;">Selenium</a> <a href="/tags/TKE/" style="font-size: 10px;">TKE</a> <a href="/tags/Ubuntu/" style="font-size: 11.25px;">Ubuntu</a> <a href="/tags/VS-Code/" style="font-size: 10px;">VS Code</a> <a href="/tags/Vs-Code/" style="font-size: 10px;">Vs Code</a> <a href="/tags/Vue/" style="font-size: 11.25px;">Vue</a> <a href="/tags/Webpack/" style="font-size: 10px;">Webpack</a> <a href="/tags/Windows/" style="font-size: 10px;">Windows</a> <a href="/tags/Winpcap/" style="font-size: 10px;">Winpcap</a> <a href="/tags/WordPress/" style="font-size: 13.75px;">WordPress</a> <a href="/tags/Youtube/" style="font-size: 11.25px;">Youtube</a> <a href="/tags/android/" style="font-size: 10px;">android</a> <a href="/tags/ansible/" style="font-size: 10px;">ansible</a> <a href="/tags/cocos2d-x/" style="font-size: 10px;">cocos2d-x</a> <a href="/tags/e6/" style="font-size: 10px;">e6</a> <a href="/tags/fitvids/" style="font-size: 10px;">fitvids</a> <a href="/tags/git/" style="font-size: 11.25px;">git</a> <a href="/tags/json/" style="font-size: 10px;">json</a> <a href="/tags/js%E9%80%86%E5%90%91/" style="font-size: 10px;">js逆向</a> <a href="/tags/kubernetes/" style="font-size: 10px;">kubernetes</a> <a href="/tags/log/" style="font-size: 10px;">log</a> <a href="/tags/logging/" style="font-size: 10px;">logging</a> <a href="/tags/matlab/" style="font-size: 11.25px;">matlab</a> <a href="/tags/python/" style="font-size: 20px;">python</a> <a href="/tags/pytube/" style="font-size: 11.25px;">pytube</a> <a href="/tags/pywin32/" style="font-size: 10px;">pywin32</a> <a href="/tags/style/" style="font-size: 10px;">style</a> <a href="/tags/tomcat/" style="font-size: 10px;">tomcat</a> <a href="/tags/ubuntu/" style="font-size: 10px;">ubuntu</a> <a href="/tags/uwsgi/" style="font-size: 10px;">uwsgi</a> <a href="/tags/vsftpd/" style="font-size: 10px;">vsftpd</a> <a href="/tags/wamp/" style="font-size: 10px;">wamp</a> <a href="/tags/wineQQ/" style="font-size: 10px;">wineQQ</a> <a href="/tags/%E4%B8%83%E7%89%9B/" style="font-size: 11.25px;">七牛</a> <a href="/tags/%E4%B8%8A%E6%B5%B7/" style="font-size: 10px;">上海</a> <a href="/tags/%E4%B8%AA%E4%BA%BA%E7%BD%91%E7%AB%99/" style="font-size: 10px;">个人网站</a> <a href="/tags/%E4%B8%BB%E9%A2%98/" style="font-size: 10px;">主题</a> <a href="/tags/%E4%BA%91%E4%BA%A7%E5%93%81/" style="font-size: 10px;">云产品</a> <a href="/tags/%E4%BA%91%E5%AD%98%E5%82%A8/" style="font-size: 10px;">云存储</a> <a href="/tags/%E4%BA%AC%E4%B8%9C%E4%BA%91/" style="font-size: 10px;">京东云</a> <a href="/tags/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/" style="font-size: 12.5px;">人工智能</a> <a href="/tags/%E4%BB%A3%E7%90%86/" style="font-size: 10px;">代理</a> <a href="/tags/%E4%BB%A3%E7%A0%81/" style="font-size: 10px;">代码</a> <a href="/tags/%E4%BB%A3%E7%A0%81%E5%88%86%E4%BA%AB%E5%9B%BE/" style="font-size: 10px;">代码分享图</a> <a href="/tags/%E4%BC%98%E5%8C%96/" style="font-size: 10px;">优化</a> <a href="/tags/%E4%BD%8D%E8%BF%90%E7%AE%97/" style="font-size: 10px;">位运算</a> <a href="/tags/%E5%85%AC%E4%BC%97%E5%8F%B7/" style="font-size: 10px;">公众号</a> <a href="/tags/%E5%88%86%E4%BA%AB/" style="font-size: 10px;">分享</a> <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F/" style="font-size: 10px;">分布式</a> <a href="/tags/%E5%88%9B%E4%B8%9A/" style="font-size: 10px;">创业</a> <a href="/tags/%E5%89%8D%E7%AB%AF/" style="font-size: 12.5px;">前端</a> <a href="/tags/%E5%8D%9A%E5%AE%A2/" style="font-size: 10px;">博客</a> <a href="/tags/%E5%8E%9F%E7%94%9FAPP/" style="font-size: 10px;">原生APP</a> <a href="/tags/%E5%8F%8D%E7%88%AC%E8%99%AB/" style="font-size: 12.5px;">反爬虫</a> <a href="/tags/%E5%91%BD%E4%BB%A4/" style="font-size: 10px;">命令</a> <a href="/tags/%E5%93%8D%E5%BA%94%E5%BC%8F%E5%B8%83%E5%B1%80/" style="font-size: 10px;">响应式布局</a> <a href="/tags/%E5%9E%83%E5%9C%BE%E9%82%AE%E4%BB%B6/" style="font-size: 10px;">垃圾邮件</a> <a href="/tags/%E5%9F%9F%E5%90%8D%E7%BB%91%E5%AE%9A/" style="font-size: 10px;">域名绑定</a> <a href="/tags/%E5%A4%8D%E7%9B%98/" style="font-size: 10px;">复盘</a> <a href="/tags/%E5%A4%A7%E4%BC%97%E7%82%B9%E8%AF%84/" style="font-size: 10px;">大众点评</a> <a href="/tags/%E5%AD%97%E4%BD%93%E5%8F%8D%E7%88%AC%E8%99%AB/" style="font-size: 10px;">字体反爬虫</a> <a href="/tags/%E5%AD%97%E7%AC%A6%E9%97%AE%E9%A2%98/" style="font-size: 10px;">字符问题</a> <a href="/tags/%E5%AD%A6%E4%B9%A0%E6%96%B9%E6%B3%95/" style="font-size: 10px;">学习方法</a> <a href="/tags/%E5%AE%89%E5%8D%93/" style="font-size: 10px;">安卓</a> <a href="/tags/%E5%AE%9E%E7%94%A8/" style="font-size: 10px;">实用</a> <a href="/tags/%E5%B0%81%E9%9D%A2/" style="font-size: 10px;">封面</a> <a href="/tags/%E5%B4%94%E5%BA%86%E6%89%8D/" style="font-size: 18.75px;">崔庆才</a> <a href="/tags/%E5%B7%A5%E5%85%B7/" style="font-size: 12.5px;">工具</a> <a href="/tags/%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/" style="font-size: 10px;">开发工具</a> <a href="/tags/%E5%BE%AE%E8%BD%AF/" style="font-size: 10px;">微软</a> <a href="/tags/%E6%80%9D%E8%80%83/" style="font-size: 10px;">思考</a> <a href="/tags/%E6%89%8B%E6%9C%BA%E8%AE%BF%E9%97%AE/" style="font-size: 10px;">手机访问</a> <a href="/tags/%E6%95%99%E7%A8%8B/" style="font-size: 10px;">教程</a> <a href="/tags/%E6%95%99%E8%82%B2/" style="font-size: 10px;">教育</a> <a href="/tags/%E6%96%B0%E4%B9%A6/" style="font-size: 12.5px;">新书</a> <a href="/tags/%E6%96%B9%E6%B3%95%E8%AE%BA/" style="font-size: 10px;">方法论</a> <a href="/tags/%E6%97%85%E6%B8%B8/" style="font-size: 10px;">旅游</a> <a href="/tags/%E6%97%A5%E5%BF%97/" style="font-size: 10px;">日志</a> <a href="/tags/%E6%9A%97%E6%97%B6%E9%97%B4/" style="font-size: 10px;">暗时间</a> <a href="/tags/%E6%9D%9C%E5%85%B0%E7%89%B9/" style="font-size: 11.25px;">杜兰特</a> <a href="/tags/%E6%A1%8C%E9%9D%A2/" style="font-size: 10px;">桌面</a> <a href="/tags/%E6%AD%8C%E5%8D%95/" style="font-size: 10px;">歌单</a> <a href="/tags/%E6%B1%9F%E5%8D%97/" style="font-size: 10px;">江南</a> <a href="/tags/%E6%B8%B8%E6%88%8F/" style="font-size: 10px;">游戏</a> <a href="/tags/%E7%84%A6%E8%99%91/" style="font-size: 10px;">焦虑</a> <a href="/tags/%E7%88%AC%E8%99%AB/" style="font-size: 16.25px;">爬虫</a> <a href="/tags/%E7%88%AC%E8%99%AB%E4%B9%A6%E7%B1%8D/" style="font-size: 11.25px;">爬虫书籍</a> <a href="/tags/%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F/" style="font-size: 10px;">环境变量</a> <a href="/tags/%E7%94%9F%E6%B4%BB%E7%AC%94%E8%AE%B0/" style="font-size: 10px;">生活笔记</a> <a href="/tags/%E7%99%BB%E5%BD%95/" style="font-size: 10px;">登录</a> <a href="/tags/%E7%9F%A5%E4%B9%8E/" style="font-size: 10px;">知乎</a> <a href="/tags/%E7%9F%AD%E4%BF%A1/" style="font-size: 10px;">短信</a> <a href="/tags/%E7%9F%AD%E4%BF%A1%E9%AA%8C%E8%AF%81%E7%A0%81/" style="font-size: 10px;">短信验证码</a> <a href="/tags/%E7%AC%94%E8%AE%B0%E8%BD%AF%E4%BB%B6/" style="font-size: 10px;">笔记软件</a> <a href="/tags/%E7%AF%AE%E7%BD%91/" style="font-size: 10px;">篮网</a> <a href="/tags/%E7%BA%B8%E5%BC%A0/" style="font-size: 10px;">纸张</a> <a href="/tags/%E7%BB%84%E4%BB%B6/" style="font-size: 10px;">组件</a> <a href="/tags/%E7%BD%91%E7%AB%99/" style="font-size: 10px;">网站</a> <a href="/tags/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/" style="font-size: 11.25px;">网络爬虫</a> <a href="/tags/%E7%BE%8E%E5%AD%A6/" style="font-size: 10px;">美学</a> <a href="/tags/%E8%82%89%E5%A4%B9%E9%A6%8D/" style="font-size: 10px;">肉夹馍</a> <a href="/tags/%E8%85%BE%E8%AE%AF%E4%BA%91/" style="font-size: 10px;">腾讯云</a> <a href="/tags/%E8%87%AA%E5%BE%8B/" style="font-size: 10px;">自律</a> <a href="/tags/%E8%A5%BF%E5%B0%91%E7%88%B7/" style="font-size: 10px;">西少爷</a> <a href="/tags/%E8%A7%86%E9%A2%91/" style="font-size: 10px;">视频</a> <a href="/tags/%E8%B0%B7%E6%AD%8C%E9%AA%8C%E8%AF%81%E7%A0%81/" style="font-size: 10px;">谷歌验证码</a> <a href="/tags/%E8%BF%90%E8%90%A5/" style="font-size: 10px;">运营</a> <a href="/tags/%E8%BF%9C%E7%A8%8B/" style="font-size: 10px;">远程</a> <a href="/tags/%E9%80%86%E5%90%91/" style="font-size: 10px;">逆向</a> <a href="/tags/%E9%85%8D%E7%BD%AE/" style="font-size: 10px;">配置</a> <a href="/tags/%E9%87%8D%E8%A3%85/" style="font-size: 10px;">重装</a> <a href="/tags/%E9%98%BF%E6%9D%9C/" style="font-size: 10px;">阿杜</a> <a href="/tags/%E9%9D%99%E8%A7%85/" style="font-size: 17.5px;">静觅</a> <a href="/tags/%E9%A2%A0%E8%A6%86/" style="font-size: 10px;">颠覆</a> <a href="/tags/%E9%A3%9E%E4%BF%A1/" style="font-size: 10px;">飞信</a> <a href="/tags/%E9%B8%BF%E8%92%99/" style="font-size: 10px;">鸿蒙</a>
              </div>
              <script>
                const tagsColors = ['#00a67c', '#5cb85c', '#d9534f', '#567e95', '#b37333', '#f4843d', '#15a287']
                const tagsElements = document.querySelectorAll('.sidebar-panel-tags .content a')
                tagsElements.forEach((item) =>
                {
                  item.style.backgroundColor = tagsColors[Math.floor(Math.random() * tagsColors.length)]
                })

              </script>
            </div>
            <div class="sidebar-panel sidebar-panel-categories sidebar-panel-active">
              <h4 class="name"> 分类 </h4>
              <div class="content">
                <ul class="category-list">
                  <li class="category-list-item"><a class="category-list-link" href="/categories/C-C/">C/C++</a><span class="category-list-count">23</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/HTML/">HTML</a><span class="category-list-count">14</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Java/">Java</a><span class="category-list-count">5</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/">JavaScript</a><span class="category-list-count">26</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">15</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Markdown/">Markdown</a><span class="category-list-count">1</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Net/">Net</a><span class="category-list-count">4</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Other/">Other</a><span class="category-list-count">39</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/PHP/">PHP</a><span class="category-list-count">27</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Paper/">Paper</a><span class="category-list-count">2</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Python/">Python</a><span class="category-list-count">261</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/TypeScript/">TypeScript</a><span class="category-list-count">2</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E4%B8%AA%E4%BA%BA%E5%B1%95%E7%A4%BA/">个人展示</a><span class="category-list-count">1</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E4%B8%AA%E4%BA%BA%E6%97%A5%E8%AE%B0/">个人日记</a><span class="category-list-count">9</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E4%B8%AA%E4%BA%BA%E8%AE%B0%E5%BD%95/">个人记录</a><span class="category-list-count">4</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E4%B8%AA%E4%BA%BA%E9%9A%8F%E7%AC%94/">个人随笔</a><span class="category-list-count">15</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E5%AE%89%E8%A3%85%E9%85%8D%E7%BD%AE/">安装配置</a><span class="category-list-count">59</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E8%B0%88/">技术杂谈</a><span class="category-list-count">88</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E6%9C%AA%E5%88%86%E7%B1%BB/">未分类</a><span class="category-list-count">1</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E7%94%9F%E6%B4%BB%E7%AC%94%E8%AE%B0/">生活笔记</a><span class="category-list-count">1</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E7%A6%8F%E5%88%A9%E4%B8%93%E5%8C%BA/">福利专区</a><span class="category-list-count">6</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E8%81%8C%E4%BD%8D%E6%8E%A8%E8%8D%90/">职位推荐</a><span class="category-list-count">2</span></li>
                </ul>
              </div>
            </div>
            <div class="sidebar-panel sidebar-panel-friends sidebar-panel-active">
              <h4 class="name"> 友情链接 </h4>
              <ul class="friends">
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/j2dub.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.findhao.net/" target="_blank" rel="noopener">FindHao</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/ou6mm.jpg">
                  </span>
                  <span class="link">
                    <a href="https://diygod.me/" target="_blank" rel="noopener">DIYgod</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/6apxu.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.51dev.com/" target="_blank" rel="noopener">IT技术社区</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://www.jankl.com/img/titleshu.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.jankl.com/" target="_blank" rel="noopener">liberalist</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/bqlbs.png">
                  </span>
                  <span class="link">
                    <a href="http://www.urselect.com/" target="_blank" rel="noopener">优社电商</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/8s88c.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.yuanrenxue.com/" target="_blank" rel="noopener">猿人学</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/2wgg5.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.yunlifang.cn/" target="_blank" rel="noopener">云立方</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/shwr6.png">
                  </span>
                  <span class="link">
                    <a href="http://lanbing510.info/" target="_blank" rel="noopener">冰蓝</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/blvoh.jpg">
                  </span>
                  <span class="link">
                    <a href="https://lengyue.me/" target="_blank" rel="noopener">冷月</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="http://qianxunclub.com/favicon.png">
                  </span>
                  <span class="link">
                    <a href="http://qianxunclub.com/" target="_blank" rel="noopener">千寻啊千寻</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/0044u.jpg">
                  </span>
                  <span class="link">
                    <a href="http://kodcloud.com/" target="_blank" rel="noopener">可道云</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/ygnpn.jpg">
                  </span>
                  <span class="link">
                    <a href="http://www.kunkundashen.cn/" target="_blank" rel="noopener">坤坤大神</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/22uv1.png">
                  </span>
                  <span class="link">
                    <a href="http://www.cenchong.com/" target="_blank" rel="noopener">岑冲博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/ev9kl.png">
                  </span>
                  <span class="link">
                    <a href="http://www.zxiaoji.com/" target="_blank" rel="noopener">张小鸡</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://www.503error.com/favicon.ico">
                  </span>
                  <span class="link">
                    <a href="https://www.503error.com/" target="_blank" rel="noopener">张志明个人博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/x714o.jpg">
                  </span>
                  <span class="link">
                    <a href="http://www.hubwiz.com/" target="_blank" rel="noopener">汇智网</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/129d8.png">
                  </span>
                  <span class="link">
                    <a href="https://www.bysocket.com/" target="_blank" rel="noopener">泥瓦匠BYSocket</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://www.xiongge.club/favicon.ico">
                  </span>
                  <span class="link">
                    <a href="https://www.xiongge.club/" target="_blank" rel="noopener">熊哥club</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/3w4fe.png">
                  </span>
                  <span class="link">
                    <a href="https://zerlong.com/" target="_blank" rel="noopener">知语</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/44hxf.png">
                  </span>
                  <span class="link">
                    <a href="http://redstonewill.com/" target="_blank" rel="noopener">红色石头</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/8g1fk.jpg">
                  </span>
                  <span class="link">
                    <a href="http://www.laodong.me/" target="_blank" rel="noopener">老董博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/wkaus.jpg">
                  </span>
                  <span class="link">
                    <a href="https://zhaoshuai.me/" target="_blank" rel="noopener">碎念</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/pgo0r.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.chenwenguan.com/" target="_blank" rel="noopener">陈文管的博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/kk82a.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.lxlinux.net/" target="_blank" rel="noopener">良许Linux教程网</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/lj0t2.jpg">
                  </span>
                  <span class="link">
                    <a href="https://tanqingbo.cn/" target="_blank" rel="noopener">IT码农</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/i8cdr.png">
                  </span>
                  <span class="link">
                    <a href="https://junyiseo.com/" target="_blank" rel="noopener">均益个人博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/chwv2.png">
                  </span>
                  <span class="link">
                    <a href="https://brucedone.com/" target="_blank" rel="noopener">大鱼的鱼塘</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/2y43o.png">
                  </span>
                  <span class="link">
                    <a href="http://bbs.nightteam.cn/" target="_blank" rel="noopener">夜幕爬虫安全论坛</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/zvc3w.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.weishidong.com/" target="_blank" rel="noopener">韦世东的技术专栏</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/ebudy.jpg">
                  </span>
                  <span class="link">
                    <a href="https://chuanjiabing.com/" target="_blank" rel="noopener">穿甲兵技术社区</a>
                  </span>
                </li>
              </ul>
            </div>
          </div>
        </aside>
        <div id="sidebar-dimmer"></div>
      </div>
    </main>
    <footer class="footer">
      <div class="footer-inner">
        <div class="copyright"> &copy; <span itemprop="copyrightYear">2021</span>
          <span class="with-love">
            <i class="fa fa-heart"></i>
          </span>
          <span class="author" itemprop="copyrightHolder">崔庆才丨静觅</span>
          <span class="post-meta-divider">|</span>
          <span class="post-meta-item-icon">
            <i class="fa fa-chart-area"></i>
          </span>
          <span title="站点总字数">2.6m</span>
          <span class="post-meta-divider">|</span>
          <span class="post-meta-item-icon">
            <i class="fa fa-coffee"></i>
          </span>
          <span title="站点阅读时长">39:54</span>
        </div>
        <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动 </div>
        <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">京ICP备18015597号-1 </a>
        </div>
        <script>
          (function ()
          {
            function leancloudSelector(url)
            {
              url = encodeURI(url);
              return document.getElementById(url).querySelector('.leancloud-visitors-count');
            }

            function addCount(Counter)
            {
              var visitors = document.querySelector('.leancloud_visitors');
              var url = decodeURI(visitors.id);
              var title = visitors.dataset.flagTitle;
              Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify(
              {
                url
              }))).then(response => response.json()).then((
              {
                results
              }) =>
              {
                if (results.length > 0)
                {
                  var counter = results[0];
                  leancloudSelector(url).innerText = counter.time + 1;
                  Counter('put', '/classes/Counter/' + counter.objectId,
                  {
                    time:
                    {
                      '__op': 'Increment',
                      'amount': 1
                    }
                  }).catch(error =>
                  {
                    console.error('Failed to save visitor count', error);
                  });
                }
                else
                {
                  Counter('post', '/classes/Counter',
                  {
                    title,
                    url,
                    time: 1
                  }).then(response => response.json()).then(() =>
                  {
                    leancloudSelector(url).innerText = 1;
                  }).catch(error =>
                  {
                    console.error('Failed to create', error);
                  });
                }
              }).catch(error =>
              {
                console.error('LeanCloud Counter Error', error);
              });
            }

            function showTime(Counter)
            {
              var visitors = document.querySelectorAll('.leancloud_visitors');
              var entries = [...visitors].map(element =>
              {
                return decodeURI(element.id);
              });
              Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify(
              {
                url:
                {
                  '$in': entries
                }
              }))).then(response => response.json()).then((
              {
                results
              }) =>
              {
                for (let url of entries)
                {
                  let target = results.find(item => item.url === url);
                  leancloudSelector(url).innerText = target ? target.time : 0;
                }
              }).catch(error =>
              {
                console.error('LeanCloud Counter Error', error);
              });
            }
            let
            {
              app_id,
              app_key,
              server_url
            } = {
              "enable": true,
              "app_id": "6X5dRQ0pnPWJgYy8SXOg0uID-gzGzoHsz",
              "app_key": "ziLDVEy73ne5HtFTiGstzHMS",
              "server_url": "https://6x5drq0p.lc-cn-n1-shared.com",
              "security": false
            };

            function fetchData(api_server)
            {
              var Counter = (method, url, data) =>
              {
                return fetch(`${api_server}/1.1${url}`,
                {
                  method,
                  headers:
                  {
                    'X-LC-Id': app_id,
                    'X-LC-Key': app_key,
                    'Content-Type': 'application/json',
                  },
                  body: JSON.stringify(data)
                });
              };
              if (CONFIG.page.isPost)
              {
                if (CONFIG.hostname !== location.hostname) return;
                addCount(Counter);
              }
              else if (document.querySelectorAll('.post-title-link').length >= 1)
              {
                showTime(Counter);
              }
            }
            let api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com`;
            if (api_server)
            {
              fetchData(api_server);
            }
            else
            {
              fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id).then(response => response.json()).then((
              {
                api_server
              }) =>
              {
                fetchData('https://' + api_server);
              });
            }
          })();

        </script>
      </div>
      <div class="footer-stat">
        <span id="cnzz_stat_icon_1279355174"></span>
        <script type="text/javascript">
          document.write(unescape("%3Cspan id='cnzz_stat_icon_1279355174'%3E%3C/span%3E%3Cscript src='https://v1.cnzz.com/z_stat.php%3Fid%3D1279355174%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));

        </script>
      </div>
    </footer>
  </div>
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/.js"></script>
  <script src="/js/schemes/pisces.js"></script>
  <script src="/.js"></script>
  <script src="/js/next-boot.js"></script>
  <script src="/.js"></script>
  <script>
    (function ()
    {
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x = document.getElementsByTagName("link");
      //Find the last canonical URL
      if (x.length > 0)
      {
        for (i = 0; i < x.length; i++)
        {
          if (x[i].rel.toLowerCase() == 'canonical' && x[i].href)
          {
            canonicalURL = x[i].href;
          }
        }
      }
      //Get protocol
      if (!canonicalURL)
      {
        curProtocol = window.location.protocol.split(':')[0];
      }
      else
      {
        curProtocol = canonicalURL.split(':')[0];
      }
      //Get current URL if the canonical URL does not exist
      if (!canonicalURL) canonicalURL = window.location.href;
      //Assign script content. Replace current URL with the canonical URL
      ! function ()
      {
        var e = /([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,
          r = canonicalURL,
          t = document.referrer;
        if (!e.test(r))
        {
          var n = (String(curProtocol).toLowerCase() === 'https') ? "https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif" : "//api.share.baidu.com/s.gif";
          t ? (n += "?r=" + encodeURIComponent(document.referrer), r && (n += "&l=" + r)) : r && (n += "?l=" + r);
          var i = new Image;
          i.src = n
        }
      }(window);
    })();

  </script>
  <script src="/js/local-search.js"></script>
  <script src="/.js"></script>
</body>

</html>
